<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>JavaScript 引用类型 | 净土</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="JavaScript 引用类型，Object，Array，Date，RegExp，Function，Number，Boolean，String，Global，Math，Map，Set，WeakMap，WeakSet，Proxy，Reflect，Promise，Iterator">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript 引用类型">
<meta property="og:url" content="http://howiefh.github.io/2015/08/28/javascript-reference-type/index.html">
<meta property="og:site_name" content="净土">
<meta property="og:description" content="JavaScript 引用类型，Object，Array，Date，RegExp，Function，Number，Boolean，String，Global，Math，Map，Set，WeakMap，WeakSet，Proxy，Reflect，Promise，Iterator">
<meta property="og:updated_time" content="2015-09-01T02:47:11.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript 引用类型">
<meta name="twitter:description" content="JavaScript 引用类型，Object，Array，Date，RegExp，Function，Number，Boolean，String，Global，Math，Map，Set，WeakMap，WeakSet，Proxy，Reflect，Promise，Iterator">
  
    <link rel="alternative" href="/atom.xml" title="净土" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="http://fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-40492061-1', 'auto');
ga('send', 'pageview');

</script>


  
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?56d2899c5e919fbf4a7b00de5d1c31dd";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">净土</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">乐不在外而在心，心以为乐，则是境皆乐；心以为苦，则无境不苦。</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-github-link" class="nav-icon" href="https://github.com/howiefh" title="Github" target="_blank"></a>
        
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed" target="_blank"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://howiefh.github.io"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-javascript-reference-type" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    
<a href="/2015/08/28/javascript-reference-type/" class="article-date">
  <time datetime="2015-08-28T04:18:03.000Z" itemprop="datePublished">2015-08-28</time>
</a>


    
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaScript/">JavaScript</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JavaScript 引用类型
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
		
		<div id="toc" class="toc-article">
			<h2 class="toc-title"><span>Contents</span></h2>
		
			<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#引用类型"><span class="toc-number">1.</span> <span class="toc-text">引用类型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Object类型"><span class="toc-number">1.1.</span> <span class="toc-text">Object类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Array_类型"><span class="toc-number">1.2.</span> <span class="toc-text">Array 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#检测数组"><span class="toc-number">1.2.1.</span> <span class="toc-text">检测数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#转换方法"><span class="toc-number">1.2.2.</span> <span class="toc-text">转换方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#栈方法"><span class="toc-number">1.2.3.</span> <span class="toc-text">栈方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#队列方法"><span class="toc-number">1.2.4.</span> <span class="toc-text">队列方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#重排序方法"><span class="toc-number">1.2.5.</span> <span class="toc-text">重排序方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#操作方法"><span class="toc-number">1.2.6.</span> <span class="toc-text">操作方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#位置方法"><span class="toc-number">1.2.7.</span> <span class="toc-text">位置方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#迭代方法"><span class="toc-number">1.2.8.</span> <span class="toc-text">迭代方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#归并方法"><span class="toc-number">1.2.9.</span> <span class="toc-text">归并方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ES6_新增方法"><span class="toc-number">1.2.10.</span> <span class="toc-text">ES6 新增方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ES7_将加入的方法"><span class="toc-number">1.2.11.</span> <span class="toc-text">ES7 将加入的方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Date_类型"><span class="toc-number">1.3.</span> <span class="toc-text">Date 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#继承的方法"><span class="toc-number">1.3.1.</span> <span class="toc-text">继承的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#日期格式化方法"><span class="toc-number">1.3.2.</span> <span class="toc-text">日期格式化方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#日期/时间组件方法"><span class="toc-number">1.3.3.</span> <span class="toc-text">日期/时间组件方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RegExp_类型"><span class="toc-number">1.4.</span> <span class="toc-text">RegExp 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#RegExp_实例属性"><span class="toc-number">1.4.1.</span> <span class="toc-text">RegExp 实例属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RegExp_实例方法"><span class="toc-number">1.4.2.</span> <span class="toc-text">RegExp 实例方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RegExp_构造函数属性"><span class="toc-number">1.4.3.</span> <span class="toc-text">RegExp 构造函数属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#模式的局限性"><span class="toc-number">1.4.4.</span> <span class="toc-text">模式的局限性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Function_类型"><span class="toc-number">1.5.</span> <span class="toc-text">Function 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#没有重载"><span class="toc-number">1.5.1.</span> <span class="toc-text">没有重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数声明与函数表达式"><span class="toc-number">1.5.2.</span> <span class="toc-text">函数声明与函数表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#作为值的函数"><span class="toc-number">1.5.3.</span> <span class="toc-text">作为值的函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数内部属性"><span class="toc-number">1.5.4.</span> <span class="toc-text">函数内部属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数属性和方法"><span class="toc-number">1.5.5.</span> <span class="toc-text">函数属性和方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#默认参数"><span class="toc-number">1.5.6.</span> <span class="toc-text">默认参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#rest参数"><span class="toc-number">1.5.7.</span> <span class="toc-text">rest参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#扩展运算符"><span class="toc-number">1.5.8.</span> <span class="toc-text">扩展运算符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#基本包装类型"><span class="toc-number">1.6.</span> <span class="toc-text">基本包装类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Boolean_类型"><span class="toc-number">1.6.1.</span> <span class="toc-text">Boolean 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Number_类型"><span class="toc-number">1.6.2.</span> <span class="toc-text">Number 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#String_类型"><span class="toc-number">1.6.3.</span> <span class="toc-text">String 类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#单体内置对象"><span class="toc-number">1.7.</span> <span class="toc-text">单体内置对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Global对象"><span class="toc-number">1.7.1.</span> <span class="toc-text">Global对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Math_对象"><span class="toc-number">1.7.2.</span> <span class="toc-text">Math 对象</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#键集合类型"><span class="toc-number">1.8.</span> <span class="toc-text">键集合类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Map_类型"><span class="toc-number">1.8.1.</span> <span class="toc-text">Map 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法"><span class="toc-number">1.8.1.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例的属性和操作方法"><span class="toc-number">1.8.1.2.</span> <span class="toc-text">实例的属性和操作方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#遍历方法"><span class="toc-number">1.8.1.3.</span> <span class="toc-text">遍历方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#与其他数据结构的互相转换"><span class="toc-number">1.8.1.4.</span> <span class="toc-text">与其他数据结构的互相转换</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WeakMap_类型"><span class="toc-number">1.8.2.</span> <span class="toc-text">WeakMap 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Set_类型"><span class="toc-number">1.8.3.</span> <span class="toc-text">Set 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法-1"><span class="toc-number">1.8.3.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Set实例的属性和方法"><span class="toc-number">1.8.3.2.</span> <span class="toc-text">Set实例的属性和方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WeakSet_类型"><span class="toc-number">1.8.4.</span> <span class="toc-text">WeakSet 类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#反射类型"><span class="toc-number">1.9.</span> <span class="toc-text">反射类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Proxy"><span class="toc-number">1.9.1.</span> <span class="toc-text">Proxy</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Reflect"><span class="toc-number">1.9.2.</span> <span class="toc-text">Reflect</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#控制抽象类型"><span class="toc-number">1.10.</span> <span class="toc-text">控制抽象类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Iteration_接口"><span class="toc-number">1.10.1.</span> <span class="toc-text">Iteration 接口</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterable_接口"><span class="toc-number">1.10.1.1.</span> <span class="toc-text">Iterable 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterator_接口"><span class="toc-number">1.10.1.2.</span> <span class="toc-text">Iterator 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#IteratorResult_接口"><span class="toc-number">1.10.1.3.</span> <span class="toc-text">IteratorResult 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例"><span class="toc-number">1.10.1.4.</span> <span class="toc-text">实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#默认实现Iterable接口的数据结构"><span class="toc-number">1.10.1.5.</span> <span class="toc-text">默认实现Iterable接口的数据结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterable接口默认的应用场合"><span class="toc-number">1.10.1.6.</span> <span class="toc-text">Iterable接口默认的应用场合</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#原生具备Iterable接口的数据结构"><span class="toc-number">1.10.1.7.</span> <span class="toc-text">原生具备Iterable接口的数据结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterable接口与Generator函数"><span class="toc-number">1.10.1.8.</span> <span class="toc-text">Iterable接口与Generator函数</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise_类型"><span class="toc-number">1.10.2.</span> <span class="toc-text">Promise 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise的含义"><span class="toc-number">1.10.2.1.</span> <span class="toc-text">Promise的含义</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法-2"><span class="toc-number">1.10.2.2.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-prototype-then()"><span class="toc-number">1.10.2.3.</span> <span class="toc-text">Promise.prototype.then()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-prototype-catch()"><span class="toc-number">1.10.2.4.</span> <span class="toc-text">Promise.prototype.catch()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-all()"><span class="toc-number">1.10.2.5.</span> <span class="toc-text">Promise.all()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-race()"><span class="toc-number">1.10.2.6.</span> <span class="toc-text">Promise.race()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-resolve()"><span class="toc-number">1.10.2.7.</span> <span class="toc-text">Promise.resolve()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-reject()"><span class="toc-number">1.10.2.8.</span> <span class="toc-text">Promise.reject()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Generator函数与Promise的结合"><span class="toc-number">1.10.2.9.</span> <span class="toc-text">Generator函数与Promise的结合</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#async函数"><span class="toc-number">1.10.2.10.</span> <span class="toc-text">async函数</span></a></li></ol></li></ol></li></ol></li></ol>
		
		</div>
		
        <p><a href="2015/08/28/javascript-grammar/">JavaScript 基本语法</a>，<a href="2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>，<a href="2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>三篇笔记是对《JavaScript 高级程序设计》和 <a href="https://github.com/ruanyf/es6tutorial/tree/5a5f9d8d492d0f925cbb6e09b10ebed9d2078d40" target="_blank" rel="external">《ECMAScript 6入门》</a>两本书的总结整理。</p>
<h1 id="引用类型">引用类型</h1><p>引用类型是一种数据结构，用于将数据和功能组织在一起。它也常被称为类，但这种称呼并不妥当。尽管 ECMAScript从技术上讲是一门面向对象的语言，但它不具备传统的面向对象语言所支持的类和接口等基本结构。引用类型有时候也被称为对象定义，因为它们描述的是一类对象所具有的属性和方法。</p>
<a id="more"></a>
<h2 id="Object类型">Object类型</h2><p>创建Object实例有两种方式，第一种是使用new操作符后跟Object构造函数，如下所示：<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = new Object();</span><br><span class="line"><span class="keyword">person</span>.name = <span class="string">"Nicholas"</span>;</span><br><span class="line"><span class="keyword">person</span>.age = 29;</span><br></pre></td></tr></table></figure></p>
<p>新对象是使用new操作符后跟一个构造函数来创建的。构造函数本身就是一个函数，只不过该函数是出于创建新对象的目的而定义的。</p>
<p>另一种方式是使用对象字面量表示法。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = &#123;</span><br><span class="line">  name : 'Nicholas',</span><br><span class="line">  age : 9</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>在最后一个属性后面添加逗号，会在IE7及更早版本和Opera中导致错误。 在使用对象字面量语法时，属性名也可以使用字符串</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = &#123;</span><br><span class="line">  'name' : 'Nicholas',</span><br><span class="line">  'age' : 9,</span><br><span class="line">  5 : true</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>这里5会被转换为字符串。</p>
<p>使用对象字面量语法时，如果留空其花括号，则可以定义只包含默认属性和方法的对象</p>
<figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = &#123;&#125;; //与 new Object()相同</span><br><span class="line"><span class="keyword">person</span>.name = <span class="string">"Nicholas"</span>;</span><br><span class="line"><span class="keyword">person</span>.age = 29;</span><br></pre></td></tr></table></figure>
<p>开发人员更青睐对象字面量语法，因为这种语法要求的代码量少，而且能够给人封装数据的感觉。实际上，对象字面量也是向函数传递大量可选参数的首选方式。最好的做法是对那些必需值使用命名参数，而使用对象字面量来封装多个可选参数。</p>
<p>在通过对象字面量定义对象时，实际上不会调用Object构造函数</p>
<p>ES6允许直接写入变量和函数，作为对象的属性和方法。这样的书写更加简洁。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> v = 'world';</span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  v,</span><br><span class="line">  <span class="keyword">method</span>() &#123;</span><br><span class="line">    <span class="keyword">return</span> '<span class="type">Hello</span>!';</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>这种写法用于函数的返回值，将会非常方便。</p>
<p>在 JavaScript也可以使用方括号表示法来访问对象的属性。在使用方括号语法时，应该将要访问的属性以字符串的形式放在方括号中。方括号语法的主要优点是可以通过变量来访问属性，例如：<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var propertyName = <span class="string">"name"</span>;</span><br><span class="line">alert(<span class="keyword">person</span><span class="comment">[propertyName]</span>); //<span class="string">"Nicholas"</span></span><br></pre></td></tr></table></figure></p>
<p>如果属性名中包含会导致语法错误的字符，或者属性名使用的是关键字或保留字，也可以使用方括号表示法。例如： <code>person[&quot;first name&quot;] = &quot;Nicholas&quot;;</code></p>
<p>除非必须使用方括号，否则建议使用点表示法。</p>
<p>ES6允许字面量定义对象时，把表达式放在方括号内作为属性名。</p>
<figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="atom">var</span> <span class="atom">lastWord</span> = <span class="string">'last word'</span>;</span><br><span class="line"></span><br><span class="line"><span class="atom">var</span> <span class="atom">a</span> = &#123;</span><br><span class="line">  <span class="string">'first word'</span>: <span class="string">'hello'</span>,</span><br><span class="line">  [<span class="atom">lastWord</span>]: <span class="string">'world'</span>,</span><br><span class="line">  [<span class="string">'h'</span>+<span class="string">'ello'</span>]() &#123;</span><br><span class="line">    <span class="atom">return</span> <span class="string">'hi'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="atom">a</span>[<span class="string">'first word'</span>] // <span class="string">"hello"</span></span><br><span class="line"><span class="atom">a</span>[<span class="atom">lastWord</span>] // <span class="string">"world"</span></span><br><span class="line"><span class="atom">a</span>[<span class="string">'last word'</span>] // <span class="string">"world"</span></span><br><span class="line"><span class="atom">a</span>.<span class="atom">hello</span>(); //<span class="atom">hi</span></span><br></pre></td></tr></table></figure>
<p>函数的name属性，返回函数名。ES6为对象方法也添加了name属性。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">person</span> = &#123;</span><br><span class="line">  sayName: function() &#123;</span><br><span class="line">    console.log(this.name);</span><br><span class="line">  &#125;,</span><br><span class="line">  get firstName() &#123;</span><br><span class="line">    return <span class="string">"Nicholas"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">person</span>.sayName.name   // <span class="string">"sayName"</span></span><br><span class="line"><span class="keyword">person</span>.firstName.name // <span class="string">"get firstName"</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，方法的name属性返回函数名（即方法名）。如果使用了取值函数，则会在方法名前加上get。如果是存值函数，方法名的前面会加上set。</p>
<p>有两种特殊情况：bind方法创造的函数，name属性返回“bound”加上原函数的名字；Function构造函数创造的函数，name属性返回“anonymous”。<br><figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">(new <span class="function"><span class="keyword">Function</span><span class="params">()</span></span>).<span class="keyword">name</span> // <span class="string">"anonymous"</span></span><br><span class="line">var doSomething = <span class="function"><span class="keyword">function</span><span class="params">()</span></span> &#123;</span><br><span class="line">  // ...</span><br><span class="line">&#125;;</span><br><span class="line">doSomething.<span class="keyword">bind</span>().<span class="keyword">name</span> // <span class="string">"bound doSomething"</span></span><br></pre></td></tr></table></figure></p>
<p><strong>Object.is()</strong>用来比较两个值是否严格相等。它与严格比较运算符（===）的行为基本一致，不同之处只有两个：一是+0不等于-0，二是NaN等于自身。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">+<span class="number">0</span> === -<span class="number">0</span> <span class="comment">//true</span></span><br><span class="line"><span class="literal">NaN</span> === <span class="literal">NaN</span> <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Object</span>.is(+<span class="number">0</span>, -<span class="number">0</span>) <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Object</span>.is(<span class="literal">NaN</span>, <span class="literal">NaN</span>) <span class="comment">// true</span></span><br></pre></td></tr></table></figure></p>
<p><strong>Object.assign方法</strong>用来将源对象（source）的所有可枚举属性，复制到目标对象（target）。它至少需要两个对象作为参数，第一个参数是目标对象，后面的参数都是源对象。只要有一个参数不是对象，就会抛出TypeError错误。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> target</span> = &#123; a: <span class="number">1</span> &#125;;</span><br><span class="line"><span class="variable"><span class="keyword">var</span> source1</span> = &#123; b: <span class="number">2</span> &#125;;</span><br><span class="line"><span class="variable"><span class="keyword">var</span> source2</span> = &#123; c: <span class="number">3</span> &#125;;</span><br><span class="line">Object.assign(target, source1, source2);</span><br><span class="line">target <span class="comment">// &#123;a:1, b:2, c:3&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>注意，如果目标对象与源对象有同名属性，或多个源对象有同名属性，则后面的属性会覆盖前面的属性。</p>
<p>assign方法有很多用处。</p>
<p><strong>1）为对象添加属性</strong><br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> Point &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(x, y) </span>&#123;</span><br><span class="line">    <span class="built_in">Object</span>.assign(<span class="keyword">this</span>, &#123;x, y&#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>2）为对象添加方法</strong><br><figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">Object</span><span class="class">.assign</span>(SomeClass.prototype, &#123;</span><br><span class="line">  <span class="tag">someMethod</span>(arg1, arg2) &#123; ··· &#125;,</span><br><span class="line">  <span class="function">anotherMethod</span>() &#123; ··· &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p><strong>3）克隆对象</strong><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">clone</span>(<span class="params">origin</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Object</span>.assign(&#123;&#125;, origin);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>不过，采用这种方法克隆，只能克隆原始对象自身的值，不能克隆它继承的值。如果想要保持继承链，可以采用下面的代码。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">clone</span>(<span class="params">origin</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> originProto = <span class="built_in">Object</span>.getPrototypeOf(origin);</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Object</span>.assign(<span class="built_in">Object</span>.create(originProto), origin);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>4）合并多个对象</strong></p>
<p>将多个对象合并到某个对象。<br><figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="reserved">const</span> merge =</span><br><span class="line">  <span class="function"><span class="params">(target, ...sources)</span> =&gt;</span> Object.assign(target, ...sources);</span><br></pre></td></tr></table></figure></p>
<p><strong>5）为属性指定默认值</strong><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> DEFAULTS = &#123;</span><br><span class="line">  logLevel: <span class="number">0</span>,</span><br><span class="line">  outputFormat: <span class="string">'html'</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">processContent</span>(<span class="params">options</span>) </span>&#123;</span><br><span class="line">  <span class="comment">//用户自定义参数options和默认配置会合并</span></span><br><span class="line">  <span class="keyword">let</span> options = <span class="built_in">Object</span>.assign(&#123;&#125;, DEFAULTS, options);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><code>__proto__属性</code> ，用来读取或设置当前对象的prototype对象。该属性一度被正式写入ES6草案，但后来又被移除。目前，所有浏览器（包括IE11）都部署了这个属性。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  __proto__: someOtherObj,</span><br><span class="line">  <span class="keyword">method</span>: function() &#123; ... &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// es5的写法</span><br><span class="line"><span class="keyword">var</span> obj = <span class="type">Object</span>.create(someOtherObj);</span><br><span class="line">obj.<span class="keyword">method</span> = function() &#123; ... &#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>Object.setPrototypeOf()</strong>方法的作用与<code>__proto__</code>相同，用来设置一个对象的prototype对象。它是ES6正式推荐的设置原型对象的方法。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 格式</span></span><br><span class="line"><span class="built_in">Object</span>.setPrototypeOf(object, prototype)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 用法</span></span><br><span class="line"><span class="keyword">var</span> o = <span class="built_in">Object</span>.setPrototypeOf(&#123;&#125;, <span class="keyword">null</span>);</span><br></pre></td></tr></table></figure>
<p><strong>Object.getPrototypeOf()</strong>方法与setPrototypeOf方法配套，用于读取一个对象的prototype对象。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">Object</span><span class="class">.getPrototypeOf</span>(<span class="tag">obj</span>);</span><br></pre></td></tr></table></figure>
<p>注意，Object.observe和Object.unobserve这两个方法不属于ES6，而是属于ES7的一部分。不过，Chrome浏览器从33版起就已经支持。</p>
<p><strong>Object.observe</strong>方法用来监听对象（以及数组）的变化。一旦监听对象发生变化，就会触发回调函数。</p>
<figure class="highlight puppet"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">var <span class="keyword">user</span> = <span class="keyword">&#123;</span><span class="keyword">&#125;</span>;</span><br><span class="line"><span class="constant">Object</span>.observe(<span class="keyword">user</span>, <span class="keyword">function(changes)&#123;</span></span><br><span class="line">  <span class="literal">changes</span>.<span class="keyword">forEach(function(change) &#123;</span></span><br><span class="line">    <span class="keyword">user</span>.fullName = <span class="keyword">user</span>.firstName+<span class="string">" "</span>+<span class="keyword">user</span>.lastName;</span><br><span class="line">  <span class="keyword">&#125;</span>);</span><br><span class="line"><span class="keyword">&#125;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">user</span>.firstName = <span class="string">'Michael'</span>;</span><br><span class="line"><span class="keyword">user</span>.lastName = <span class="string">'Jackson'</span>;</span><br><span class="line"><span class="keyword">user</span>.fullName // <span class="string">'Michael Jackson'</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Object.observer方法监听user对象。一旦该对象发生变化，就自动生成fullName属性。</p>
<p>一般情况下，Object.observe方法接受两个参数，第一个参数是监听的对象，第二个函数是一个回调函数。一旦监听对象发生变化（比如新增或删除一个属性），就会触发这个回调函数。很明显，利用这个方法可以做很多事情，比如自动更新DOM。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> div = $(<span class="string">"#foo"</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">Object</span>.observe(user, <span class="function"><span class="keyword">function</span>(<span class="params">changes</span>)</span>&#123;</span><br><span class="line">  changes.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">change</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> fullName = user.firstName+<span class="string">" "</span>+user.lastName;</span><br><span class="line">    div.text(fullName);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，只要user对象发生变化，就会自动更新DOM。如果配合jQuery的change方法，就可以实现数据对象与DOM对象的双向自动绑定。</p>
<p>回调函数的changes参数是一个数组，代表对象发生的变化。下面是一个更完整的例子。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">observer</span>(<span class="params">changes</span>)</span>&#123;</span><br><span class="line">  changes.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">change</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'发生变动的属性：'</span> + change.name);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'变动前的值：'</span> + change.oldValue);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'变动后的值：'</span> + change.object[change.name]);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'变动类型：'</span> + change.type);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">Object</span>.observe(o, observer);</span><br></pre></td></tr></table></figure>
<p>参照上面代码，Object.observe方法指定的回调函数，接受一个数组（changes）作为参数。该数组的成员与对象的变化一一对应，也就是说，对象发生多少个变化，该数组就有多少个成员。每个成员是一个对象（change），它的name属性表示发生变化源对象的属性名，oldValue属性表示发生变化前的值，object属性指向变动后的源对象，type属性表示变化的种类。基本上，change对象是下面的样子。</p>
<p>Object.observe方法目前共支持监听六种变化。</p>
<ul>
<li>add：添加属性</li>
<li>update：属性值的变化</li>
<li>delete：删除属性</li>
<li>setPrototype：设置原型</li>
<li>reconfigure：属性的attributes对象发生变化</li>
<li>preventExtensions：对象被禁止扩展（当一个对象变得不可扩展时，也就不必再监听了）</li>
</ul>
<p>Object.observe方法还可以接受第三个参数，用来指定监听的事件种类。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">Object</span><span class="class">.observe</span>(<span class="tag">o</span>, <span class="tag">observer</span>, <span class="attr_selector">['delete']</span>);</span><br></pre></td></tr></table></figure>
<p>上面的代码表示，只在发生delete事件时，才会调用回调函数。</p>
<p><strong>Object.unobserve</strong>方法用来取消监听。</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">Object</span><span class="class">.unobserve</span>(<span class="tag">o</span>, <span class="tag">observer</span>);</span><br></pre></td></tr></table></figure>
<p>目前，ES7有一个<a href="https://github.com/sebmarkbage/ecmascript-rest-spread" target="_blank" rel="external">提案</a>，将rest参数/扩展运算符（…）引入对象。Babel转码器已经支持这项功能。</p>
<p><strong>1）Rest参数</strong></p>
<p>Rest参数用于从一个对象取值，相当于将所有可遍历的、但尚未被读取的属性，分配到指定的对象上面。所有的键和它们的值，都会拷贝到新对象上面。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">let &#123; x, y, ...z &#125; = &#123; <span class="string">x:</span> <span class="number">1</span>, <span class="string">y:</span> <span class="number">2</span>, <span class="string">a:</span> <span class="number">3</span>, <span class="string">b:</span> <span class="number">4</span> &#125;;</span><br><span class="line">x <span class="comment">// 1</span></span><br><span class="line">y <span class="comment">// 2</span></span><br><span class="line">z <span class="comment">// &#123; a: 3, b: 4 &#125;</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，变量z是Rest参数所在的对象。它获取等号右边的所有尚未读取的键（a和b），将它们和它们的值拷贝过来。</p>
<p>注意，Rest参数的拷贝是浅拷贝，即如果一个键的值是复合类型的值（数组、对象、函数）、那么Rest参数拷贝的是这个值的引用，而不是这个值的副本。</p>
<p>另外，Rest参数不会拷贝继承自原型对象的属性。</p>
<figure class="highlight gcode"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">let <span class="preprocessor">o1</span> = &#123; a: <span class="number">1</span> &#125;;</span><br><span class="line">let <span class="preprocessor">o2</span> = &#123; b: <span class="number">2</span> &#125;;</span><br><span class="line"><span class="preprocessor">o2</span>.__proto__ = <span class="preprocessor">o1</span>;</span><br><span class="line">let <span class="preprocessor">o3</span> = &#123; ...<span class="preprocessor">o2</span> &#125;;</span><br><span class="line"><span class="preprocessor">o3</span> <span class="comment">// &#123; b: 2 &#125;</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，对象o3是o2的复制，但是只复制了o2自身的属性，没有复制它的原型对象o1的属性。</p>
<p><strong>2）扩展运算符</strong></p>
<p>扩展运算符用于取出参数对象的所有可遍历属性，拷贝到当前对象之中。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> z <span class="subst">=</span> &#123; a: <span class="number">3</span>, b: <span class="number">4</span> &#125;;</span><br><span class="line"><span class="keyword">let</span> n <span class="subst">=</span> &#123; <span class="attribute">...</span>z &#125;;</span><br><span class="line">n <span class="comment">// &#123; a: 3, b: 4 &#125;</span></span><br></pre></td></tr></table></figure>
<p>这等同于使用<code>Object.assign</code>方法。</p>
<p>扩展运算符的参数对象之中，如果有取值函数<code>get</code>，这个函数是会执行的。</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 并不会抛出错误，因为x属性只是被定义，但没执行</span></span><br><span class="line"><span class="keyword">let</span> aWithXGetter = &#123;</span><br><span class="line">  ...a,</span><br><span class="line">  <span class="function"><span class="keyword">get</span> <span class="title">x</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="function">throws new <span class="title">Error</span>(<span class="params"><span class="string">'not thrown yet'</span></span>)</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 会抛出错误，因为x属性被执行了</span></span><br><span class="line"><span class="keyword">let</span> runtimeError = &#123;</span><br><span class="line">  ...a,</span><br><span class="line">  ...&#123;</span><br><span class="line">    <span class="function"><span class="keyword">get</span> <span class="title">x</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="function">throws new <span class="title">Error</span>(<span class="params"><span class="string">'thrown now'</span></span>)</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>如果扩展运算符的参数是null或undefined，这个两个值会被忽略，不会报错。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> emptyObject <span class="subst">=</span> &#123; <span class="attribute">...</span><span class="built_in">null</span>, <span class="attribute">...</span>undefined &#125;; <span class="comment">// 不报错</span></span><br></pre></td></tr></table></figure>
<h2 id="Array_类型">Array 类型</h2><p>ECMAScript 数组的每一项可以保存任何类型的数据</p>
<p>创建数组的基本方式有两种。第一种是使用 Array 构造函数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="keyword">new</span> <span class="built_in">Array</span>();</span><br></pre></td></tr></table></figure></p>
<p>如果预先知道数组要保存的项目数量，也可以给构造函数传递该数量，而该数量会自动变成length属性的值。例如，下面的代码将创建length值为20的数组。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">20</span>);</span><br></pre></td></tr></table></figure></p>
<p>也可以向Array构造函数传递数组中应该包含的项。以下代码创建了一个包含3个字符串值的数组：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>);</span><br></pre></td></tr></table></figure></p>
<p>当然，给构造函数传递一个值也可以创建数组。但这时候问题就复杂一点了，因为如果传递的是数值，则会按照该数值创建包含给定项数的数组；而如果传递的是其他类型的参数，则会创建包含那个值的只有一项的数组。下面就两个例子：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>); <span class="comment">// 创建一个包含3 项的数组</span></span><br><span class="line"><span class="keyword">var</span> names = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"Greg"</span>); <span class="comment">// 创建一个包含1 项，即字符串"Greg"的数组</span></span><br></pre></td></tr></table></figure></p>
<p>另外,在使用 Array 构造函数时也可以省略 new 操作符。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> colors = <span class="built_in">Array</span>(<span class="number">3</span>); <span class="comment">// 创建一个包含3 项的数组</span></span><br><span class="line"><span class="keyword">var</span> names = <span class="built_in">Array</span>(<span class="string">"Greg"</span>); <span class="comment">// 创建一个包含1 项，即字符串"Greg"的数组</span></span><br></pre></td></tr></table></figure></p>
<p>创建数组的第二种基本方式是使用数组字面量表示法。数组字面量由一对包含数组项的方括号表示，多个数组项之间以逗号隔开，如下所示：<br><figure class="highlight autohotkey"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var colors = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>]<span class="comment">; // 创建一个包含3 个字符串的数组</span></span><br><span class="line">var names = []<span class="comment">; // 创建一个空数组</span></span><br><span class="line">var values = [<span class="number">1</span>,<span class="number">2</span>,]<span class="comment">; // 不要这样！这样会创建一个包含2 或3 项的数组，对于IE早期版本(&lt;=8)这里将会是三项，最后一项是undefined，下面同理</span></span><br><span class="line">var options = [,,,,,]<span class="comment">; // 不要这样！这样会创建一个包含5 或6 项的数组</span></span><br></pre></td></tr></table></figure></p>
<p>ECMAScript数组的大小是可以动态调整的，即可以随着数据的添加自动增长以容纳新增数据。</p>
<p>与对象一样，在使用数组字面量表示法时，也不会调用Array构造函数</p>
<p>数组的length属性很有特点——它不是只读的。因此，通过设置这个属性，可以从数组的末尾移除项或向数组中添加新项。请看下面的例子：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> colors</span> = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>]; <span class="comment">// 创建一个包含3 个字符串的数组</span></span><br><span class="line">colors.length = <span class="number">2</span>;</span><br><span class="line">alert(colors[<span class="number">2</span>]); <span class="comment">//undefined</span></span><br></pre></td></tr></table></figure></p>
<p>当把一个值放在超出当前数组大小的位置上时,数组就会重新计算其长度值,即长度值<br>等于最后一项的索引加 1:<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> colors</span> = [<span class="string">"red"</span>, <span class="string">"blue"</span>, <span class="string">"green"</span>];</span><br><span class="line">colors[<span class="number">99</span>] = <span class="string">"black"</span>;</span><br><span class="line">alert(colors.length); <span class="comment">// 100</span></span><br></pre></td></tr></table></figure></p>
<p>位置3到位置98实际上都是不存在的，所以访问它们都将返回undefined。</p>
<p>数组最多可以包含4 294 967 295个项，这几乎已经能够满足任何编程需求了。如果想添加的项数超过这个上限值，就会发生异常。而创建一个初始大小与这个上限值接近的数组，则可能会导致运行时间超长的脚本错误。</p>
<h3 id="检测数组">检测数组</h3><p>instanceof 操作符的问题在于,它假定只有一个全局执行环境。如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的 Array 构造函数。如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。</p>
<p>ECMAScript 5新增了Array.isArray()方法。这个方法的目的是最终确定某个值到底是不是数组，而不管它是在哪个全局执行环境中创建的</p>
<h3 id="转换方法">转换方法</h3><p>数组的toString()方法会返回由数组中每个值的字符串形式拼接而成的一个以逗号分隔的字符串。为了创建这个字符串会调用数组每一项的 toString() 方法。toLocaleString()与toString()有些类似，只不过是调用每项的toLocaleString()。而调用 valueOf()返回的还是数组。</p>
<p>如果使用 join() 方法,则可以使用不同的分隔符来构建这个字符串。 join() 方法只接收一个参数,即用作分隔符的字符串,然后返回包含所有数组项的字符串。如果不给 join() 方法传入任何值,或者给它传入 undefined ,则使用逗号作为分隔符。IE7 及更早版本会错误的使用字符串 “undefined” 作为分隔符。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var colors = [<span class="string">"red"</span>, <span class="string">"green"</span>, <span class="string">"blue"</span>];</span><br><span class="line">alert<span class="params">(colors.join<span class="params">()</span>)</span>; <span class="comment">//red,green,blue</span></span><br><span class="line">alert<span class="params">(colors.join<span class="params">(<span class="string">"||"</span>)</span>)</span>; <span class="comment">//red||green||blue</span></span><br></pre></td></tr></table></figure>
<p>如果数组中的某一项的值是 null 或者 undefined，那么该值在 join()、toLocaleString()、toString() 和 valueOf() 方法返回的结果中以空字符串表示。</p>
<h3 id="栈方法">栈方法</h3><p>ECMAScript为数组专门提供了push()和pop()方法，以便实现类似栈的行为。这两个方法会改变length的值<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> colors</span> = new Array();<span class="comment">// 创建一个数组</span></span><br><span class="line"><span class="variable"><span class="keyword">var</span> count</span> = colors.push(<span class="string">"red"</span>, <span class="string">"green"</span>); <span class="comment">// 推入两项</span></span><br><span class="line">alert(count); <span class="comment">//2</span></span><br><span class="line"><span class="variable"><span class="keyword">var</span> item</span> = colors.pop();<span class="comment">// 取得最后一项</span></span><br><span class="line">alert(item); <span class="comment">//"black"</span></span><br><span class="line">alert(colors.length); <span class="comment">//1</span></span><br></pre></td></tr></table></figure></p>
<h3 id="队列方法">队列方法</h3><p>shift() 能够移除数组中的第一个项并返回该项,同时将数组长度减 1。结合使用 shift() 和 push() 方法,可以像使用队列一样使用数组。</p>
<p>unshift()与shift()的用途相反：它能在数组前端添加任意个项并返回新数组的长度。因此，同时使用unshift()和pop()方法，可以从相反的方向来模拟队列，即在数组的前端添加项，从数组末端移除项</p>
<h3 id="重排序方法">重排序方法</h3><p>数组中已经存在两个可以直接用来重排序的方法：reverse()和 sort()</p>
<p>sort()方法会调用每个数组项的 toString()转型方法，然后比较得到的字符串，以确定如何排序。即使数组中的每一项都是数值，sort()方法比较的也是字符串</p>
<p>sort()方法可以接收一个比较函数作为参数，以便我们指定哪个值位于哪个值的前面。比较函数接收两个参数，如果第一个参数应该位于第二个之前则返回一个负数，如果两个参数相等则返回0，如果第一个参数应该位于第二个之后则返回一个正数</p>
<figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> compare(<span class="keyword">value</span><span class="number">1</span>, <span class="keyword">value</span><span class="number">2</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">value</span><span class="number">1</span> &lt; <span class="keyword">value</span><span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">value</span><span class="number">1</span> &gt; <span class="keyword">value</span><span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">var values = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">10</span>, <span class="number">15</span>];</span><br><span class="line">values.sort(compare);</span><br><span class="line">alert(values); <span class="comment">//0,1,5,10,15</span></span><br><span class="line">values.sort();</span><br><span class="line">alert(values); <span class="comment">//0,1,10,15,5</span></span><br></pre></td></tr></table></figure>
<p>对于数值类型或者其 valueOf() 方法会返回数值类型的对象类型,可以使用一个更简单的比较函数。这个函数只要用第二个值减第一个值即可。正数减负数可能溢出<br><figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> compare(<span class="keyword">value</span><span class="number">1</span>, <span class="keyword">value</span><span class="number">2</span>)&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">value</span><span class="number">2</span> - <span class="keyword">value</span><span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="操作方法">操作方法</h3><p>concat()方法可以基于当前数组中的所有项创建一个新数组。具体来说，这个方法会先创建当前数组一个副本，然后将接收到的参数添加到这个副本的末尾，最后返回新构建的数组。在没有给concat()方法传递参数的情况下，它只是复制当前数组并返回副本。</p>
<p>slice()能够基于当前数组中的一或多个项创建一个新数组。slice()方法可以接受一或两个参数，即要返回项的起始和结束位置。在只有一个参数的情况下, slice() 方法返回从该参数指定位置开始到当前数组末尾的所有项。如果有两个参数,该方法返回起始和结束位置之间的项——但不包括结束位置的项。注意, slice() 方法不会影响原始数组。注意, slice() 方法不会影响原始数组。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> colors</span> = [<span class="string">"red"</span>, <span class="string">"green"</span>, <span class="string">"blue"</span>, <span class="string">"yellow"</span>, <span class="string">"purple"</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> colors2</span> = colors.slice(<span class="number">1</span>);</span><br><span class="line"><span class="variable"><span class="keyword">var</span> colors3</span> = colors.slice(<span class="number">1</span>,<span class="number">4</span>);</span><br><span class="line">alert(colors2); <span class="comment">//green,blue,yellow,purple</span></span><br><span class="line">alert(colors3); <span class="comment">//green,blue,yellow</span></span><br></pre></td></tr></table></figure>
<p>如果slice()方法的参数中有一个负数，则用数组长度加上该数来确定相应的位置。例如，在一个包含5项的数组上调用slice(-2,-1)与调用slice(3,4)得到的结果相同。如果结束位置小于起始位置，则返回空数组。</p>
<p>splice()方法，这个方法恐怕要算是最强大的数组方法了，它有很多种用法。splice()的主要用途是向数组的中部插入项，但使用这种方法的方式则有如下3种。</p>
<ul>
<li>删除：可以删除任意数量的项，只需指定 2 个参数：要删除的第一项的位置和要删除的项数。例如，splice(0,2)会删除数组中的前两项。</li>
<li>插入：可以向指定位置插入任意数量的项，只需提供3个参数：起始位置、0（要删除的项数）和要插入的项。如果要插入多个项，可以再传入第四、第五，以至任意多个项。例如，splice(2,0,”red”,”green”)会从当前数组的位置2开始插入字符串”red”和”green”。</li>
<li>替换：可以向指定位置插入任意数量的项，且同时删除任意数量的项，只需指定 3 个参数：起始位置、要删除的项数和要插入的任意数量的项。插入的项数不必与删除的项数相等。例如，splice (2,1,”red”,”green”)会删除当前数组位置 2 的项，然后再从位置 2 开始插入字符串”red”和”green”。</li>
</ul>
<p>splice()方法始终都会返回一个数组，该数组中包含从原始数组中删除的项（如果没有删除任何项，则返回一个空数组）。</p>
<h3 id="位置方法">位置方法</h3><p>ECMAScript 5为数组实例添加了两个位置方法：indexOf()和lastIndexOf()。这两个方法都接收两个参数：要查找的项和（可选的）表示查找起点位置的索引。其中，indexOf()方法从数组的开头（位置0）开始向后查找，lastIndexOf()方法则从数组的末尾开始向前查找。</p>
<p>这两个方法都返回要查找的项在数组中的位置，或者在没找到的情况下返回-1。在比较第一个参数与数组中的每一项时，会使用全等操作符；也就是说，要求查找的项必须严格相等（就像使用===一样）。</p>
<h3 id="迭代方法">迭代方法</h3><p>ECMAScript 5为数组定义了5个迭代方法。每个方法都接收两个参数：要在每一项上运行的函数和（可选的）运行该函数的作用域对象——影响 this 的值。传入这些方法中的函数会接收三个参数：数组项的值、该项在数组中的位置和数组对象本身。根据使用的方法不同，这个函数执行后的返回值可能会也可能不会影响方法的返回值。以下是这5个迭代方法的作用。</p>
<ul>
<li>every()：对数组中的每一项运行给定函数，如果该函数对每一项都返回true，则返回 true。</li>
<li>filter()：对数组中的每一项运行给定函数，返回该函数会返回true的项组成的数组。</li>
<li>forEach()：对数组中的每一项运行给定函数。这个方法没有返回值。</li>
<li>map()：对数组中的每一项运行给定函数，返回每次函数调用的结果组成的数组。</li>
<li>some()：对数组中的每一项运行给定函数，如果该函数对任一项返回true，则返回true。</li>
</ul>
<p>以上方法都不会修改数组中的包含的值。</p>
<h3 id="归并方法">归并方法</h3><p>ECMAScript 5还新增了两个归并数组的方法：reduce()和 reduceRight()。这两个方法都会迭代数组的所有项，然后构建一个最终返回的值。其中，reduce()方法从数组的第一项开始，逐个遍历到最后。而reduceRight()则从数组的最后一项开始，向前遍历到第一项。</p>
<p>这两个方法都接收两个参数：一个在每一项上调用的函数和（可选的）作为归并基础的初始值。传给 reduce()和 reduceRight()的函数接收 4个参数：前一个值、当前值、项的索引和数组对象。这个函数返回的任何值都会作为第一个参数自动传给下一项。第一次迭代发生在数组的第二项上，因此第一个参数是数组的第一项，第二个参数就是数组的第二项。</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> values = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];</span><br><span class="line"><span class="keyword">var</span> sum = values.reduce(<span class="function"><span class="keyword">function</span><span class="params">(prev, cur, <span class="keyword">index</span>, <span class="keyword">array</span>)</span><span class="comment">&#123;</span><br><span class="line">  return prev + cur;</span><br><span class="line">&#125;</span>);</span></span><br><span class="line">alert(sum); <span class="comment">//15</span></span><br><span class="line"><span class="keyword">var</span> values = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];</span><br></pre></td></tr></table></figure>
<p>第一次执行回调函数, prev 是 1, cur 是 2。第二次, prev 是 3(1 加 2 的结果), cur 是 3(数组的第三项)。这个过程会持续到把数组中的每一项都访问一遍,最后返回结果。</p>
<h3 id="ES6_新增方法">ES6 新增方法</h3><ul>
<li><p>Array.from()<br>  用于将两类对象转为真正的数组：类似数组的对象（array-like object）和可遍历（iterable）的对象（包括ES6新增的数据结构Set和Map）</p>
<p>  Array.from方法可以将函数的arguments对象，转为数组。</p>
<p>  任何有length属性的对象，都可以通过Array.from方法转为数组。</p>
<p>  Array.from()还可以接受第二个参数，作用类似于数组的map方法，用来对每个元素进行处理。<code>Array.from(arrayLike, x =&gt; x * x);</code>等同于<code>Array.from(arrayLike).map(x =&gt; x * x);</code></p>
<p>  Array.from()的一个应用是，将字符串转为数组，然后返回字符串的长度。这样可以避免JavaScript将大于\uFFFF的Unicode字符，算作两个字符的bug。</p>
</li>
<li>Array.of()<br>  用于将一组值，转换为数组。这个方法的主要目的，是弥补数组构造函数Array()的不足。因为参数个数的不同，会导致Array()的行为有差异。<code>Array(3) // [undefined, undefined, undefined]</code></li>
<li><p>数组实例的find()和findIndex()<br>  数组实例的find方法，用于找出第一个符合条件的数组成员。它的参数是一个回调函数，所有数组成员依次执行该回调函数，直到找出第一个返回值为true的成员，然后返回该成员。如果没有符合条件的成员，则返回undefined。<code>var found = [1, 4, -5, 10].find((n) =&gt; n &lt; 0);</code></p>
<p>  find方法的回调函数可以接受三个参数，依次为当前的值、当前的位置和原数组。</p>
<p>  数组实例的findIndex方法的用法与find方法非常类似，返回第一个符合条件的数组成员的位置，如果所有成员都不符合条件，则返回-1。</p>
<p>  这两个方法都可以接受第二个参数，用来绑定回调函数的this对象。</p>
</li>
<li>数组实例的fill()<br>  使用给定值，填充一个数组。fill()还可以接受第二个和第三个参数，用于指定填充的起始位置和结束位置。</li>
<li><p>数组实例的entries()，keys()和values()<br>  ES6提供三个新的方法——entries()，keys()和values()——用于遍历数组。它们都返回一个既实现了Iterable又实现了Iterator接口的对象，且该对象<code>Symbol.iterator</code>方法返回其自身，可以用for…of循环进行遍历，唯一的区别是keys()是对键名的遍历、values()是对键值的遍历，entries()是对键值对的遍历。</p>
  <figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="reserved">let</span> [index, elem] <span class="keyword">of</span> [<span class="string">'a'</span>, <span class="string">'b'</span>].entries()) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(index, elem);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="ES7_将加入的方法">ES7 将加入的方法</h3><ul>
<li>数组实例的includes()<br>  返回一个布尔值，表示某个数组是否包含给定的值。该方法属于ES7。该方法的第二个参数表示搜索的起始位置，默认为0。</li>
<li><p>Array.observe()，Array.unobserve()<br>  这两个方法用于监听（取消监听）数组的变化，指定回调函数。</p>
<p>  它们的用法与Object.observe和Object.unobserve方法完全一致，也属于ES7的一部分，唯一的区别是，对象可监听的变化一共有六种，而数组只有四种：add、update、delete、splice（数组的length属性发生变化）</p>
</li>
</ul>
<p>此外ES7将加入数组推导（array comprehension），以提供简洁写法，允许直接通过现有数组生成新数组。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> a1</span> = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> a2</span> = [<span class="keyword">for</span> (i of a1) i * <span class="number">2</span>];</span><br><span class="line">a2 <span class="comment">// [2, 4, 6, 8]</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码表示，通过for…of结构，数组a2直接在a1的基础上生成。</p>
<p>注意，数组推导中，for…of结构总是写在最前面，返回的表达式写在最后面。</p>
<p>for…of后面还可以附加if语句，用来设定循环的限制条件。</p>
<p>需要注意的是，数组推导的方括号构成了一个单独的作用域，在这个方括号中声明的变量类似于使用let语句声明的变量。</p>
<h2 id="Date_类型">Date 类型</h2><p>ECMAScript 中的 Date 类型是在早期 Java 中的 java.util.Date 类基础上构建的。</p>
<p>在调用Date 构造函数而不传递参数的情况下，新创建的对象自动获得当前日期和时间。如果想根据特定的日期和时间创建日期对象,必须传入表示该日期的毫秒数(即从 UTC 时间 1970 年 1 月 1 日午夜起至该日期止经过的毫秒数)。为了简化这一计算过程,ECMAScript 提供了两个方法: Date.parse()和 Date.UTC() 。</p>
<p>Date.parse()方法接收一个表示日期的字符串参数，然后尝试根据这个字符串返回相应日期的毫秒数。ECMA-262没有定义Date.parse()应该支持哪种日期格式，因此这个方法的行为因实现而异，而且通常是因地区而异。</p>
<p>如果传入Date.parse()方法的字符串不能表示日期，那么它会返回NaN。实际上，如果直接将表示日期的字符串传递给Date构造函数，也会在后台调用Date.parse()</p>
<p>Date.UTC()方法同样也返回表示日期的毫秒数，但它与 Date.parse()在构建值时使用不同的信息。Date.UTC()的参数分别是年份、基于 0的月份（一月是 0，二月是 1，以此类推）、月中的哪一天（1到 31）、小时数（0到 23）、分钟、秒以及毫秒数。在这些参数中，只有前两个参数（年和月）是必需的。如果没有提供月中的天数，则假设天数为 1；如果省略其他参数，则统统假设为 0。</p>
<p>Date 构造函数会模仿 Date.parse()和 Date.UTC()，但模仿后者有一点明显不同：日期和时间都基于本地时区而非GMT来创建。不过，Date 构造函数接收的参数仍然与Date.UTC()相同。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> y2k1 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="built_in">Date</span>.UTC(<span class="number">2000</span>, <span class="number">0</span>));</span><br><span class="line"><span class="keyword">var</span> y2k2 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">2000</span>, <span class="number">0</span>);</span><br><span class="line"><span class="keyword">var</span> someDate1 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="built_in">Date</span>.parse(<span class="string">"May 25, 2004"</span>));</span><br><span class="line"><span class="keyword">var</span> someDate2 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">"May 25, 2004"</span>);</span><br></pre></td></tr></table></figure>
<p>ECMAScript 5添加了Data.now()方法，返回表示调用这个方法时的日期和时间的毫秒数。这个方法简化了使用Data对象分析代码的工作。</p>
<p>使用+操作符把Data对象转换成数值，也可以达到同样的目的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//取得开始时间 和Date.now()等效</span></span><br><span class="line"><span class="keyword">var</span> start = +<span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre></td></tr></table></figure>
<h3 id="继承的方法">继承的方法</h3><p>Date类型的toLocaleString()方法会按照与浏览器设置的地区相适应的格式返回日期和时间。这大致意味着时间格式中会包含AM或PM，但不会包含时区信息（当然，具体的格式会因浏览器而异）。而toString()方法则通常返回带有时区信息的日期和时间，其中时间一般以军用时间（即小时的范围是0到23）表示。</p>
<p>至于Date类型的valueOf()方法，则根本不返回字符串，而是返回日期的毫秒表示。</p>
<h3 id="日期格式化方法">日期格式化方法</h3><p>Date类型还有一些专门用于将日期格式化为字符串的方法，这些方法如下。</p>
<ul>
<li>toDateString()——以特定于实现的格式显示星期几、月、日和年；</li>
<li>toTimeString()——以特定于实现的格式显示时、分、秒和时区；</li>
<li>toLocaleDateString()——以特定于地区的格式显示星期几、月、日和年；</li>
<li>toLocaleTimeString()——以特定于实现的格式显示时、分、秒；</li>
<li>toUTCString()——以特定于实现的格式完整的UTC日期。</li>
</ul>
<p>与toLocaleString()和toString()方法一样，以上这些字符串格式方法的输出也是因浏览器而异的，因此没有哪一个方法能够用来在用户界面中显示一致的日期信息。</p>
<p>除了前面介绍的方法之外,还有一个名叫 toGMTString() 的方法,这是一个与toUTCString() 等价的方法,其存在目的在于确保向后兼容。不过,ECMAScript 推荐现在编写的代码一律使用 toUTCString() 方法。</p>
<h3 id="日期/时间组件方法">日期/时间组件方法</h3><p>剩下还未介绍的Date类型的方法（如下表所示），都是直接取得和设置日期值中特定部分的方法了。需要注意的是，UTC日期指的是在没有时区偏差的情况下（将日期转换为GMT时间）的日期值。</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>getTime()</td>
<td>返回表示日期的毫秒数;与 valueOf() 方法返回的值相同</td>
</tr>
<tr>
<td>setTime( 毫秒 )</td>
<td>以毫秒数设置日期,会改变整个日期</td>
</tr>
<tr>
<td>getFullYear()</td>
<td>取得4位数的年份(如2007而非仅07)</td>
</tr>
<tr>
<td>getUTCFullYear()</td>
<td>返回UTC日期的4位数年份</td>
</tr>
<tr>
<td>setFullYear( 年 )</td>
<td>设置日期的年份。传入的年份值必须是4位数字(如2007而非仅07)</td>
</tr>
<tr>
<td>setUTCFullYear( 年 )</td>
<td>设置UTC日期的年份。传入的年份值必须是4位数字(如2007而非仅07)</td>
</tr>
<tr>
<td>getMonth()</td>
<td>返回日期中的月份,其中0表示一月,11表示十二月</td>
</tr>
<tr>
<td>getUTCMonth()</td>
<td>返回UTC日期中的月份,其中0表示一月,11表示十二月</td>
</tr>
<tr>
<td>setMonth( 月 )</td>
<td>设置日期的月份。传入的月份值必须大于0,超过11则增加年份</td>
</tr>
<tr>
<td>setUTCMonth( 月 )</td>
<td>设置UTC日期的月份。传入的月份值必须大于0,超过11则增加年份</td>
</tr>
<tr>
<td>getDate()</td>
<td>返回日期月份中的天数(1到31)</td>
</tr>
<tr>
<td>getUTCDate()</td>
<td>返回UTC日期月份中的天数(1到31)</td>
</tr>
<tr>
<td>setDate( 日 )</td>
<td>设置日期月份中的天数。如果传入的值超过了该月中应有的天数,则增加月份</td>
</tr>
<tr>
<td>setUTCDate( 日 )</td>
<td>设置UTC日期月份中的天数。如果传入的值超过了该月中应有的天数,则增加月份</td>
</tr>
<tr>
<td>getDay()</td>
<td>返回日期中星期的星期几(其中0表示星期日,6表示星期六)</td>
</tr>
<tr>
<td>getUTCDay()</td>
<td>返回UTC日期中星期的星期几(其中0表示星期日,6表示星期六)</td>
</tr>
<tr>
<td>getHours()</td>
<td>返回日期中的小时数(0到23)</td>
</tr>
<tr>
<td>getUTCHours()</td>
<td>返回UTC日期中的小时数(0到23)</td>
</tr>
<tr>
<td>setHours( 时 )</td>
<td>设置日期中的小时数。传入的值超过了23则增加月份中的天数</td>
</tr>
<tr>
<td>setUTCHours( 时 )</td>
<td>设置UTC日期中的小时数。传入的值超过了23则增加月份中的天数</td>
</tr>
<tr>
<td>getMinutes()</td>
<td>返回日期中的分钟数(0到59)</td>
</tr>
<tr>
<td>getUTCMinutes()</td>
<td>返回UTC日期中的分钟数(0到59)</td>
</tr>
<tr>
<td>setMinutes( 分 )</td>
<td>设置日期中的分钟数。传入的值超过59则增加小时数</td>
</tr>
<tr>
<td>setUTCMinutes( 分 )</td>
<td>设置UTC日期中的分钟数。传入的值超过59则增加小时数</td>
</tr>
<tr>
<td>getSeconds()</td>
<td>返回日期中的秒数(0到59)</td>
</tr>
<tr>
<td>getUTCSeconds()</td>
<td>返回UTC日期中的秒数(0到59)</td>
</tr>
<tr>
<td>setSeconds( 秒 )</td>
<td>设置日期中的秒数。传入的值超过了59会增加分钟数</td>
</tr>
<tr>
<td>setUTCSeconds( 秒 )</td>
<td>设置UTC日期中的秒数。传入的值超过了59会增加分钟数</td>
</tr>
<tr>
<td>getMilliseconds()</td>
<td>返回日期中的毫秒数</td>
</tr>
<tr>
<td>getUTCMilliseconds()</td>
<td>返回UTC日期中的毫秒数</td>
</tr>
<tr>
<td>setMilliseconds( 毫秒 )</td>
<td>设置日期中的毫秒数</td>
</tr>
<tr>
<td>setUTCMilliseconds( 毫秒 )</td>
<td>设置UTC日期中的毫秒数</td>
</tr>
<tr>
<td>getTimezoneOffset()</td>
<td>返回本地时间与UTC时间相差的分钟数。例如,美国东部标准时间返回300。在某地进入夏令时的情况下,这个值会有所变化</td>
</tr>
</tbody>
</table>
<h2 id="RegExp_类型">RegExp 类型</h2><p>使用下面类似 Perl 的语法,就可以创建一个正则表达式。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> expression = <span class="regexp">/ pattern /</span> flags ;</span><br></pre></td></tr></table></figure></p>
<p>其中的模式(pattern)部分可以是任何简单或复杂的正则表达式,可以包含字符类、限定符、分组、向前查找以及反向引用。每个正则表达式都可带有一或多个标志(flags),用以标明正则表达式的行为。正则表达式的匹配模式支持下列 3 个标志。</p>
<ul>
<li>g :表示全局(global)模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时立即停止;</li>
<li>i :表示不区分大小写(case-insensitive)模式,即在确定匹配项时忽略模式与字符串的大小写;</li>
<li>m :表示多行(multiline)模式,即在到达一行文本末尾时还会继续查找下一行中是否存在与模式匹配的项。<br>ES6中新增两个标志</li>
<li>u :表示“Unicode模式”，用来正确处理大于\uFFFF的Unicode字符。也就是说，会正确处理四个字节的UTF-16编码。</li>
<li>y :表示“粘连”（sticky）模式。y修饰符的作用与g修饰符类似，也是全局匹配，后一次匹配都从上一次匹配成功的下一个位置开始。不同之处在于，g修饰符只要剩余位置中存在匹配就可，而y修饰符确保匹配必须从剩余的第一个位置开始，这也就是“粘连”的涵义。</li>
</ul>
<figure class="highlight gradle"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">var s = <span class="string">"𠮷"</span>;</span><br><span class="line"><span class="comment">//如果不添加u修饰符，正则表达式就会认为字符串为两个字符，从而匹配失败。</span></span><br><span class="line"><span class="regexp">/^.$/</span>.test(s) <span class="comment">// false</span></span><br><span class="line"><span class="regexp">/^.$/u</span>.test(s) <span class="comment">// true</span></span><br><span class="line"><span class="comment">//如果不加u修饰符，正则表达式无法识别\u&#123;61&#125;这种表示法，只会认为这匹配61个连续的u。</span></span><br><span class="line"><span class="regexp">/\u&#123;61&#125;/u</span>.test(<span class="string">'a'</span>) <span class="comment">// true</span></span><br><span class="line"><span class="regexp">/\u&#123;20BB7&#125;/u</span>.test(<span class="string">'𠮷'</span>) <span class="comment">// true</span></span><br><span class="line"><span class="comment">//使用u修饰符后，所有量词都会正确识别大于码点大于0xFFFF的Unicode字符。</span></span><br><span class="line"><span class="regexp">/𠮷&#123;2&#125;/</span>.test(<span class="string">'𠮷𠮷'</span>) <span class="comment">// false</span></span><br><span class="line"><span class="regexp">/𠮷&#123;2&#125;/u</span>.test(<span class="string">'𠮷𠮷'</span>) <span class="comment">// true</span></span><br><span class="line"><span class="comment">//u修饰符也影响到预定义模式，能否正确识别码点大于0xFFFF的Unicode字符。\S是预定义模式</span></span><br><span class="line"><span class="regexp">/^\S$/</span>.test(<span class="string">'𠮷'</span>) <span class="comment">// false</span></span><br><span class="line"><span class="regexp">/^\S$/u</span>.test(<span class="string">'𠮷'</span>) <span class="comment">// true</span></span><br><span class="line"><span class="comment">//有些Unicode字符的编码不同，但是字型很相近，比如，\u004B与\u212A都是大写的K。</span></span><br><span class="line"><span class="regexp">/[a-z]/i</span>.test(<span class="string">'\u212A'</span>) <span class="comment">// false</span></span><br><span class="line"><span class="regexp">/[a-z]/iu</span>.test(<span class="string">'\u212A'</span>) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>y修饰符号隐含了头部匹配的标志<code>ˆ</code>。y修饰符的设计本意，就是让头部匹配的标志ˆ在全局匹配中都有效。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> s</span> = <span class="string">"aaa_aa_a"</span>;</span><br><span class="line"><span class="variable"><span class="keyword">var</span> r1</span> = /a+/g;</span><br><span class="line"><span class="variable"><span class="keyword">var</span> r2</span> = /a+/y;</span><br><span class="line">r1.exec(s) <span class="comment">// ["aaa"]</span></span><br><span class="line">r2.exec(s) <span class="comment">// ["aaa"]</span></span><br><span class="line">r1.exec(s) <span class="comment">// ["aa"]</span></span><br><span class="line"><span class="comment">//和g一样都是从_aa_a开始，但是y标志要求必须以a开头，所以返回null</span></span><br><span class="line">r2.exec(s) <span class="comment">// null</span></span><br></pre></td></tr></table></figure></p>
<p>如果同时使用g修饰符和y修饰符，则y修饰符覆盖g修饰符。</p>
<p>模式中使用的所有元字符都必须转义。正则表达式中的元字符包括： <code>( [ { \ ^ $ | ) ? * + .]}</code></p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="regexp">//</span> 匹配所有以<span class="string">"at"</span>结尾的 <span class="number">3</span> 个字符的组合,不区分大小写</span><br><span class="line"><span class="reserved">var</span> pattern3 = <span class="regexp">/.at/gi</span>;</span><br><span class="line"><span class="regexp">//</span> 匹配所有<span class="string">".at"</span>,不区分大小写</span><br><span class="line"><span class="reserved">var</span> pattern4 = <span class="regexp">/\.at/gi</span>;</span><br></pre></td></tr></table></figure>
<p>这些例子都是以字面量形式来定义的正则表达式。另一种创建正则表达式的方式是使用RegExp 构造函数,它接收两个参数:一个是要匹配的字符串模式,另一个是可选的标志字符串。可以使用字面量定义的任何表达式,都可以使用构造函数来定义,如下面的例子所示。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 匹配第一个"bat"或"cat",不区分大小写</span></span><br><span class="line"><span class="keyword">var</span> pattern1 = <span class="regexp">/[bc]at/i</span>;</span><br><span class="line"><span class="comment">// 与 pattern1 相同,只不过是使用构造函数创建的</span></span><br><span class="line"><span class="keyword">var</span> pattern2 = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">"[bc]at"</span>, <span class="string">"i"</span>);</span><br></pre></td></tr></table></figure></p>
<p>要注意的是，传递给RegExp构造函数的两个参数都是字符串（ES5不能把正则表达式字面量传递给RegExp构造函数，ES6支持传递正则表达式字面量，如果同时有第二个标识参数，将覆盖字面量中的标识）。由于RegExp构造函数的模式参数是字符串，所以在某些情况下要对字符进行双重转义。所有元字符都必须双重转义，那些已经转义过的字符也是如此，例如<code>\n</code>（字符<code>\</code>在字符串中通常被转义为<code>\\</code>，而在正则表达式字符串中就会变成<code>\\\\</code>）。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ES6中</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="regexp">/abc/ig</span>, <span class="string">'i'</span>).flags; <span class="comment">//"i"</span></span><br></pre></td></tr></table></figure></p>
<p>使用正则表达式字面量和使用 RegExp 构造函数创建的正则表达式不一样。在ECMAScript 3中，正则表达式字面量始终会共享同一个RegExp实例，而使用构造函数创建的每一个新RegExp实例都是一个新实例。<br><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> re = null, i;</span><br><span class="line"><span class="keyword">for</span> (i=0; i &lt; 10; i++)&#123;</span><br><span class="line">  re = /<span class="keyword">cat</span>/<span class="keyword">g</span>;</span><br><span class="line">  re.<span class="keyword">test</span>(<span class="string">"catastrophe"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>循环中,即使是循环体中指定的,但实际上只为 /cat/ 创建了一个 RegExp 实例。由于实例属性(下一节介绍实例属性)不会重置,所以在循环中再次调用 test() 方法会失败。这是因为第一次调用 test() 找到了 “cat” ,但第二次调用是从索引为 3 的字符(上一次匹配的末尾)开始的,所以就找不到它了。由于会测试到字符串末尾,所以下一次再调用 test() 就又从开头开始了。</p>
<p>ECMAScript 5明确规定，使用正则表达式字面量必须像直接调用RegExp构造函数一样，每次都创建新的RegExp实例</p>
<h3 id="RegExp_实例属性">RegExp 实例属性</h3><p>RegExp的每个实例都具有下列属性，通过这些属性可以取得有关模式的各种信息。</p>
<ul>
<li>global：布尔值，表示是否设置了g标志。</li>
<li>ignoreCase：布尔值，表示是否设置了i标志。</li>
<li>lastIndex：整数，表示开始搜索下一个匹配项的字符位置，从0算起。</li>
<li>multiline：布尔值，表示是否设置了m标志。</li>
<li>source：正则表达式的字符串表示，按照字面量形式而非传入构造函数中的字符串模式返回。<br>ES6新增属性</li>
<li>sticky:布尔值，表示是否设置了y标志。</li>
<li>flags: 字符串，表示正则表达式的标志</li>
</ul>
<p>通过这些属性可以获知一个正则表达式的各方面信息，但却没有多大用处，因为这些信息全都包含在模式声明中。</p>
<h3 id="RegExp_实例方法">RegExp 实例方法</h3><p>RegExp对象的主要方法是exec()，该方法是专门为捕获组而设计的。exec()接受一个参数，即要应用模式的字符串，然后返回包含第一个匹配项信息的数组；或者在没有匹配项的情况下返回null。返回的数组虽然是Array 的实例，但包含两个额外的属性：index 和input。其中，index 表示匹配项在字符串中的位置，而 input 表示应用正则表达式的字符串。在数组中，第一项是与整个模式匹配的字符串，其他项是与模式中的捕获组匹配的字符串（如果模式中没有捕获组，则该数组只包含一项）。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var <span class="built_in">text</span> = <span class="string">"mom and dad and baby"</span>;</span><br><span class="line">var pattern = /mom<span class="params">( and dad<span class="params">( and baby)</span>?)</span>?/gi;</span><br><span class="line">var matches = pattern.exec<span class="params">(text)</span>;</span><br><span class="line">alert<span class="params">(matches.index)</span>; <span class="comment">// 0</span></span><br><span class="line">alert<span class="params">(matches.input)</span>; <span class="comment">// "mom and dad and baby"</span></span><br><span class="line">alert<span class="params">(matches[<span class="number">0</span>])</span>; <span class="comment">// "mom and dad and baby"</span></span><br><span class="line">alert<span class="params">(matches[<span class="number">1</span>])</span>; <span class="comment">// " and dad and baby"</span></span><br><span class="line">alert<span class="params">(matches[<span class="number">2</span>])</span>; <span class="comment">// " and baby"</span></span><br></pre></td></tr></table></figure>
<p>对于 exec()方法而言，即使在模式中设置了全局标志（g），它每次也只会返回一个匹配项。在不设置全局标志的情况下，在同一个字符串上多次调用 exec()将始终返回第一个匹配项的信息。而在设置全局标志的情况下，每次调用exec()则都会在字符串中继续查找新匹配项</p>
<p>IE 的 JavaScript 实现在 lastIndex 属性上存在偏差，即使在非全局模式下，lastIndex属性每次也会变化。</p>
<p>正则表达式的第二个方法是 test()，它接受一个字符串参数。在模式与该参数匹配的情况下返回true；否则，返回 false。在只想知道目标字符串与某个模式是否匹配，但不需要知道其文本内容的情况下，使用这个方法非常方便</p>
<p>RegExp实例继承的toLocaleString()和toString()方法都会返回正则表达式的字面量，与创建正则表达式的方式无关</p>
<p>正则表达式的valueOf()方法返回正则表达式本身。</p>
<h3 id="RegExp_构造函数属性">RegExp 构造函数属性</h3><p>RegExp 构造函数属性分别有一个长属性名和一个短属性名（Opera是例外，它不支持短属性名）。下表列出了RegExp构造函数的属性。</p>
<table>
<thead>
<tr>
<th>长属性名</th>
<th>短属性名</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>input</td>
<td>$_</td>
<td>最近一次要匹配的字符串。Opera未实现此属性</td>
</tr>
<tr>
<td>lastMatch</td>
<td>$&amp;</td>
<td>最近一次的匹配项。Opera未实现此属性</td>
</tr>
<tr>
<td>lastParen</td>
<td>$+</td>
<td>最近一次匹配的捕获组。Opera未实现此属性</td>
</tr>
<tr>
<td>leftContext</td>
<td>$`</td>
<td>input字符串中lastMatch之前的文本</td>
</tr>
<tr>
<td>multiline</td>
<td>$*</td>
<td>布尔值,表示是否所有表达式都使用多行模式。IE和Opera未实现此属性</td>
</tr>
<tr>
<td>rightContext</td>
<td>$’</td>
<td>Input字符串中lastMatch之后的文本</td>
</tr>
</tbody>
</table>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">var <span class="built_in">text</span> = <span class="string">"this has been a short summer"</span>;</span><br><span class="line">var pattern = /<span class="params">(.)</span>hort/g;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="params">(pattern.test<span class="params">(text)</span>)</span>&#123;</span><br><span class="line">  alert<span class="params">(RegExp.input)</span>; <span class="comment">// this has been a short summer</span></span><br><span class="line">  alert<span class="params">(RegExp.leftContext)</span>; <span class="comment">// this has been a</span></span><br><span class="line">  alert<span class="params">(RegExp.rightContext)</span>; <span class="comment">// summer</span></span><br><span class="line">  alert<span class="params">(RegExp.lastMatch)</span>; <span class="comment">// short</span></span><br><span class="line">  alert<span class="params">(RegExp.lastParen)</span>; <span class="comment">// s</span></span><br><span class="line">  alert<span class="params">(RegExp.multiline)</span>; <span class="comment">// false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>RegExp构造函数的各个属性返回了下列值：</p>
<ul>
<li>input属性返回了原始字符串；</li>
<li>leftContext属性返回了单词short之前的字符串，而rightContext属性则返回了short之后的字符串；</li>
<li>lastMatch属性返回最近一次与整个正则表达式匹配的字符串，即short；</li>
<li>lastParen 属性返回最近一次匹配的捕获组,即例子中的s</li>
</ul>
<p>由于短属性名大都不是有效的ECMAScript标识符，因此必须通过方括号语法来访问它们</p>
<p>除了上面介绍的几个属性之外，还有多达9个用于存储捕获组的构造函数属性。访问这些属性的语法是 RegExp.$1、RegExp.$2…RegExp.$9，分别用于存储第一、第二……第九个匹配的捕获组。在调用exec()或test()方法时，这些属性会被自动填充。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var <span class="built_in">text</span> = <span class="string">"this has been a short summer"</span>;</span><br><span class="line">var pattern = /<span class="params">(..)</span>or<span class="params">(.)</span>/g;</span><br><span class="line"><span class="keyword">if</span> <span class="params">(pattern.test<span class="params">(text)</span>)</span>&#123;</span><br><span class="line">  alert<span class="params">(RegExp.$<span class="number">1</span>)</span>;</span><br><span class="line">  alert<span class="params">(RegExp.$<span class="number">2</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>字符串必须转义，才能作为正则模式。有人提议作为RegExp对象的静态方法RegExp.escape()，放入ES7。该方法用于将字符串转义，但是最终这个方法没有被加入。</p>
<p>目前，该方法可以用下面的escapeRegExp函数或者垫片模块<a href="https://github.com/ljharb/regexp.escape" target="_blank" rel="external">regexp.escape</a>实现。<br><figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">function escapeRegExp(str) <span class="special">&#123;</span></span><br><span class="line">  return str.replace(/<span class="special">[</span><span class="command">\-</span><span class="command">\[</span><span class="command">\]</span><span class="command">\/</span><span class="command">\&#123;</span><span class="command">\&#125;</span><span class="command">\(</span><span class="command">\)</span><span class="command">\*</span><span class="command">\+</span><span class="command">\?</span><span class="command">\.</span><span class="command">\\</span><span class="command">\^</span><span class="command">\$</span><span class="command">\|</span><span class="special">]</span>/g, "<span class="command">\\</span><span class="formula">$<span class="special">&amp;</span>");</span><br><span class="line"><span class="special">&#125;</span></span><br><span class="line">let str = '/path/to/resource.html?search=query';</span><br><span class="line">escapeRegExp(str)</span><br><span class="line">// "<span class="command">\/</span>path<span class="command">\/</span>to<span class="command">\/</span>resource<span class="command">\.</span>html<span class="command">\?</span>search=query"</span></span><br></pre></td></tr></table></figure></p>
<h3 id="模式的局限性">模式的局限性</h3><p>ECMAScript 正则表达式不支持的特性(要了解更多相关信息。</p>
<ul>
<li>匹配字符串开始和结尾的 \A 和 \Z 锚，但支持以插入符号(^)和美元符号($)来匹配字符串的开始和结尾。</li>
<li>向后查找(lookbehind),但完全支持向前查找(lookahead)<br>。</li>
<li>并集和交集类</li>
<li>原子组(atomic grouping)</li>
<li>Unicode 支持(单个字符除外,如 \uFFFF )</li>
<li>命名的捕获组，但支持编号的捕获组。</li>
<li>s (single,单行)和 x (free-spacing,无间隔)匹配模式</li>
<li>条件匹配</li>
<li>正则表达式注释</li>
</ul>
<h2 id="Function_类型">Function 类型</h2><p>说起来 ECMAScript中什么最有意思，我想那莫过于函数了——而有意思的根源，则在于函数实际上是对象。每个函数都是Function类型的实例，而且都与其他引用类型一样具有属性和方法。<strong>由于函数是对象，因此函数名实际上也是一个指向函数对象的指针，不会与某个函数绑定</strong>。</p>
<p>函数通常是使用函数声明语法定义的。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span> <span class="params">(num1, num2)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> num1 + num2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>下面是使用函数表达式定义函数的方式，和上面效果是一样的。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="keyword">function</span><span class="params">(num1, num2)</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> num1 + num2;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>在使用函数表达式定义函数时，没有必要使用函数名——通过变量sum即可以引用函数。另外，还要注意函数末尾有一个分号，就像声明其他变量时一样。</p>
<p>最后一种定义函数的方式是使用Function构造函数。Function构造函数可以接收任意数量的参数，但最后一个参数始终都被看成是函数体，而前面的参数则枚举出了新函数的参数。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="keyword">new</span> <span class="function"><span class="keyword">Function</span><span class="params">(<span class="string">"num1"</span>, <span class="string">"num2"</span>, <span class="string">"return num1 + num2"</span>)</span></span>; <span class="comment">// 不推荐，因为这种语法会导致解析两次代码(第一次是解析常规 ECMAScript 代码,第二次是解析传入构造函数中的字符串)</span></span><br></pre></td></tr></table></figure></p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span><span class="params">(num1, num2)</span>&#123;</span></span><br><span class="line">  return num1 + num2;</span><br><span class="line">&#125;</span><br><span class="line">alert<span class="params">(sum<span class="params">(<span class="number">10</span>,<span class="number">10</span>)</span>)</span>; <span class="comment">//20</span></span><br><span class="line">var anotherSum = sum;</span><br><span class="line">alert<span class="params">(anotherSum<span class="params">(<span class="number">10</span>,<span class="number">10</span>)</span>)</span>; <span class="comment">//20</span></span><br></pre></td></tr></table></figure>
<p><strong>使用不带圆括号的函数名是访问函数指针，而非调用函数</strong></p>
<h3 id="没有重载">没有重载</h3><p>将函数名想象为指针，也有助于理解为什么 ECMAScript中没有函数重载的概念。在创建第二个同名函数时,实际上覆盖了引用第一个函数的函数名变量。</p>
<h3 id="函数声明与函数表达式">函数声明与函数表达式</h3><p>解析器会率先读取函数声明，并使其在执行任何代码之前可用（可以访问）；至于函数表达式，则必须等到解析器执行到它所在的代码行，才会真正被解释执行</p>
<p>在代码开始执行之前，解析器就已经通过一个名为函数声明提升（function declaration hoisting）的过程，读取并将函数声明添加到执行环境中。对代码求值时，JavaScript引擎在第一遍会声明函数并将它们放到源代码树的顶部</p>
<figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="built_in">sum</span>(<span class="number">10</span>,<span class="number">10</span>));</span><br><span class="line"><span class="function"><span class="keyword">function</span></span> <span class="built_in">sum</span>(num1, num2)&#123;</span><br><span class="line">  <span class="keyword">return</span> num1 + num2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的例子可以正常运行，但是下面的运行时会抛出错误<br><figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="built_in">sum</span>(<span class="number">10</span>,<span class="number">10</span>));</span><br><span class="line">var <span class="built_in">sum</span> = <span class="function"><span class="keyword">function</span><span class="params">(num1, num2)</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> num1 + num2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>也可以同时使用函数声明和函数表达式，例如var sum = function sum(){}。不过，这种语法在Safari中会导致错误。</p>
<h3 id="作为值的函数">作为值的函数</h3><p>因为 ECMAScript中的函数名本身就是变量，所以函数也可以作为值来使用。也就是说，不仅可以像传递参数一样把一个函数传递给另一个函数，而且可以将一个函数作为另一个函数的结果返回（将函数返回这是一种很有用的技巧）</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callSomeFunction</span><span class="params">(someFunction, someArgument)</span></span>&#123; <span class="comment">//someFunction是一个函数</span></span><br><span class="line">  <span class="keyword">return</span> someFunction(someArgument);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="函数内部属性">函数内部属性</h3><p>在函数内部，有两个特殊的对象：arguments和this。arguments是一个类数组对象，包含着传入函数中的所有参数。虽然 arguments 的主要用途是保存函数参数，但这个对象还有一个名叫callee的属性，该属性是一个指针，指向拥有这个arguments对象的函数。<br><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function factorial(<span class="built_in">num</span>)&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">num</span> &lt;=<span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// return num * factorial(num - 1); 和下面效果相同，但是如果引用函数的变量名不是factorial而是var a = factorial，同时factorial被指向另一个函数，通过a调用该方法，那么这样就会有问题了</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">num</span> * arguments.callee(<span class="built_in">num</span>-<span class="number">1</span>); <span class="comment">//通过这种方法，消除了和函数名的耦合</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>函数内部的另一个特殊对象是 this ,其行为与 Java 和 C#中的 this 大致类似。this引用的是函数据以执行的环境对象——或者也可以说是this值（当在网页的全局作用域中调用函数时，this对象引用的就是window）。</p>
<p>一定要牢记，函数的名字仅仅是一个包含指针的变量而已。</p>
<p>ECMAScript 5也规范化了另一个函数对象的属性：caller。除了 Opera的早期版本不支持，其他浏览器都支持这个 ECMAScript 3并没有定义的属性。这个属性中保存着调用当前函数的函数的引用，如果是在全局作用域中调用当前函数，它的值为null。</p>
<p>同样，为了实现更松散的耦合，可以通过arguments.callee.caller访问调用当前函数的函数的引用</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">outer</span><span class="params">()</span>&#123;</span></span><br><span class="line">  inner<span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">inner</span><span class="params">()</span>&#123;</span></span><br><span class="line">  alert<span class="params">(arguments.callee.caller)</span>;</span><br><span class="line">&#125;</span><br><span class="line">outer<span class="params">()</span>;</span><br></pre></td></tr></table></figure>
<p>当函数在严格模式下运行时，访问 arguments.callee 会导致错误。ECMAScript 5 还定义了arguments.caller属性，但在严格模式下访问它也会导致错误，而在非严格模式下这个属性始终是undefined。定义这个属性是为了分清arguments.caller 和函数的caller 属性。以上变化都是为了加强这门语言的安全性，这样第三方代码就不能在相同的环境里窥视其他代码了。 严格模式还有一个限制：不能为函数的caller属性赋值，否则会导致错误。</p>
<h3 id="函数属性和方法">函数属性和方法</h3><p>ECMAScript 中的函数是对象，因此函数也有属性和方法。每个函数都包含两个属性：length 和prototype。其中，length 属性表示函数希望接收的命名参数（形参）的个数</p>
<p>对于ECMAScript中的引用类型而言，prototype是保存它们所有实例方法的真正所在。换句话说，诸如toString()和valueOf()等方法实际上都保存在prototype名下，只不过是通过各自对象的实例访问罢了。在创建自定义引用类型以及实现继承时，prototype属性的作用是极为重要的（第6章将详细介绍）。在ECMAScript 5中，prototype属性是不可枚举的，因此使用for-in无法发现。</p>
<p>每个函数都包含两个非继承而来的方法：apply()和 call()。这两个方法的用途都是在特定的作用域中调用函数，实际上等于设置函数体内this对象的值。首先，apply()方法接收两个参数：一个是在其中运行函数的作用域，另一个是参数数组。其中，第二个参数可以是 Array 的实例，也可以是arguments对象</p>
<p>下例中，因为是在全局作用域中调用的,所以传入的就是 window 对象<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span>(<span class="params">num1, num2</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> num1 + num2;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callSum1</span>(<span class="params">num1, num2</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> sum.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>); <span class="comment">// 传入 arguments 对象</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callSum2</span>(<span class="params">num1, num2</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> sum.apply(<span class="keyword">this</span>, [num1, num2]); <span class="comment">// 传入数组</span></span><br><span class="line">&#125;</span><br><span class="line">alert(callSum1(<span class="number">10</span>,<span class="number">10</span>)); <span class="comment">//20</span></span><br><span class="line">alert(callSum2(<span class="number">10</span>,<span class="number">10</span>)); <span class="comment">//20</span></span><br></pre></td></tr></table></figure></p>
<p>在严格模式下，未指定环境对象而调用函数，则 this 值不会转型为 window。除非明确把函数添加到某个对象或者调用 apply()或 call()，否则 this 值将是undefined</p>
<p>call() 方法与 apply()方法的作用相同，它们的区别仅在于接收参数的方式不同。对于 call()方法而言，第一个参数是this值没有变化，变化的是其余参数都直接传递给函数。换句话说，在使用call()方法时,传递给函数的参数必须逐个列举出来</p>
<p>传递参数并非apply()和call()真正的用武之地；它们真正强大的地方是能够扩充函数赖以运行的作用域。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">window.<span class="built_in">color</span> = <span class="string">"red"</span>;</span><br><span class="line">var o = &#123; <span class="built_in">color</span>: <span class="string">"blue"</span> &#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayColor</span><span class="params">()</span>&#123;</span></span><br><span class="line">  alert<span class="params">(this.color)</span>;</span><br><span class="line">&#125;</span><br><span class="line">sayColor<span class="params">()</span>; <span class="comment">//red</span></span><br><span class="line">sayColor.call<span class="params">(this)</span>;<span class="comment">//red</span></span><br><span class="line">sayColor.call<span class="params">(window)</span>; <span class="comment">//red</span></span><br><span class="line">sayColor.call<span class="params">(o)</span>; <span class="comment">//blue</span></span><br></pre></td></tr></table></figure>
<p>使用call()（或apply()）来扩充作用域的最大好处，就是对象不需要与方法有任何耦合关系。如上sayColor方法就没有和具体对象耦合</p>
<p>ECMAScript 5还定义了一个方法：bind()。这个方法会创建一个函数的实例，其 this 值会被绑定到传给bind()函数的值</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">window.<span class="built_in">color</span> = <span class="string">"red"</span>;</span><br><span class="line">var o = &#123; <span class="built_in">color</span>: <span class="string">"blue"</span> &#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sayColor</span><span class="params">()</span>&#123;</span></span><br><span class="line">  alert<span class="params">(this.color)</span>;</span><br><span class="line">&#125;</span><br><span class="line">var objectSayColor = sayColor.bind<span class="params">(o)</span>;</span><br><span class="line">objectSayColor<span class="params">()</span>; <span class="comment">//blue</span></span><br></pre></td></tr></table></figure>
<p>每个函数继承的 toLocaleString()和 toString()方法始终都返回函数的代码</p>
<p>另外一个继承的valueOf()方法同样也只返回函数代码。</p>
<h3 id="默认参数">默认参数</h3><p>ES6允许为函数的参数设置默认值，即直接写在参数定义的后面。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">log</span><span class="params">(x, y = 'World')</span> &#123;</span></span><br><span class="line">  console.<span class="built_in">log</span><span class="params">(x, y)</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">log</span><span class="params">('Hello')</span> <span class="comment">// Hello World</span></span><br></pre></td></tr></table></figure></p>
<p>默认值的写法非常灵活，下面是一个为对象属性设置默认值的例子。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function fetch(url, &#123; body = '', <span class="keyword">method</span> = '<span class="type">GET</span>', headers = &#123;&#125; &#125;)&#123;</span><br><span class="line">  console.log(<span class="keyword">method</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，传入函数fetch的第二个参数是一个对象，调用的时候可以为它的三个属性设置默认值。</p>
<p>甚至还可以设置双重默认值。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function fetch(url, &#123; <span class="keyword">method</span> = '<span class="type">GET</span>' &#125; = &#123;&#125;)&#123;</span><br><span class="line">  console.log(<span class="keyword">method</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，调用函数fetch时，如果不含第二个参数，则默认值为一个空对象；如果包含第二个参数，则它的method属性默认值为GET。</p>
<p>定义了默认值的参数，必须是函数的尾部参数，其后不能再有其他无默认值的参数。</p>
<p>如果传入undefined，将触发该参数等于默认值，null则没有这个效果。</p>
<p>指定了默认值以后，函数的length属性，将返回没有指定默认值的参数个数。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span><span class="params">(a, b, c = 5)</span></span>&#123;&#125;).length <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></p>
<p>利用参数默认值，可以指定某一个参数不得省略，如果省略就抛出一个错误。<br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">function throwIfMissing() &#123;&#10;  throw new Error(&#39;Missing parameter&#39;);&#10;&#125;&#10;&#10;function foo(mustBeProvided = throwIfMissing()) &#123;&#10;  return mustBeProvided;&#10;&#125;&#10;&#10;foo()&#10;// Error: Missing parameter</span><br></pre></td></tr></table></figure></p>
<p>上面代码的foo函数，如果调用的时候没有参数，就会调用默认值throwIfMissing函数，从而抛出一个错误。</p>
<p>从上面代码还可以看到，参数mustBeProvided的默认值等于throwIfMissing函数的运行结果（即函数名之后有一对圆括号），这表明参数的默认值不是在定义时执行，而是在运行时执行（即如果参数已经赋值，默认值中的函数就不会运行），这与python语言不一样。</p>
<p>另一个需要注意的地方是，参数默认值所处的作用域，不是全局作用域，而是函数作用域。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var x = <span class="number">1</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span><span class="params">(x, y = x)</span> &#123;</span></span><br><span class="line">  console.<span class="built_in">log</span><span class="params">(y)</span>;</span><br><span class="line">&#125;</span><br><span class="line">foo<span class="params">(<span class="number">2</span>)</span> <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，参数y的默认值等于x，由于处在函数作用域，所以y等于参数x，而不是全局变量x。</p>
<p>参数默认值可以与解构赋值，联合起来使用。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span><span class="params">(&#123;x, y = <span class="number">5</span>&#125;)</span> &#123;</span></span><br><span class="line">  console.<span class="built_in">log</span><span class="params">(x, y)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">foo<span class="params">(&#123;&#125;)</span> <span class="comment">// undefined, 5</span></span><br><span class="line">foo<span class="params">(&#123;x: <span class="number">1</span>&#125;)</span> <span class="comment">// 1, 5</span></span><br><span class="line">foo<span class="params">(&#123;x: <span class="number">1</span>, y: <span class="number">2</span>&#125;)</span> <span class="comment">// 1, 2</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，foo函数的参数是一个对象，变量x和y用于解构赋值，y有默认值5。</p>
<h3 id="rest参数">rest参数</h3><p>ES6引入rest参数（形式为“…变量名”），用于获取函数的多余参数，这样就不需要使用arguments对象了。rest参数搭配的变量是一个数组，该变量将多余的参数放入数组中。（和Java的变长参数类似）</p>
<p>注意，rest参数之后不能再有其他参数（即只能是最后一个参数），否则会报错。</p>
<p>函数的length属性，不包括rest参数。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span><span class="params">(a, <span class="rest_arg">...b</span>)</span> </span>&#123;&#125;).length  <span class="comment">// 1</span></span><br></pre></td></tr></table></figure></p>
<h3 id="扩展运算符">扩展运算符</h3><p>扩展运算符（spread）是三个点（…）。它好比rest参数的逆运算，将一个数组转为用逗号分隔的参数序列。该运算符主要用于函数调用。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//下面max,push 方法不接受数组</span></span><br><span class="line"><span class="comment">// ES6的写法</span></span><br><span class="line">Math.max(...[<span class="number">14</span>, <span class="number">3</span>, <span class="number">77</span>])</span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line">Math.max(<span class="number">14</span>, <span class="number">3</span>, <span class="number">77</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES5的写法</span></span><br><span class="line"><span class="variable"><span class="keyword">var</span> arr1</span> = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> arr2</span> = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line">Array.prototype.push.apply(arr1, arr2);</span><br><span class="line"><span class="comment">// ES6的写法</span></span><br><span class="line"><span class="variable"><span class="keyword">var</span> arr1</span> = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> arr2</span> = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line">arr1.push(...arr2);</span><br><span class="line"></span><br><span class="line"><span class="variable"><span class="keyword">var</span> a</span> = [<span class="number">1</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> b</span> = [<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> c</span> = [<span class="number">6</span>, <span class="number">7</span>];</span><br><span class="line"><span class="variable"><span class="keyword">var</span> d</span> = [<span class="number">0</span>, ...a, ...b, <span class="number">5</span>, ...c];</span><br></pre></td></tr></table></figure></p>
<p>上面代码其实也提供了，将一个数组拷贝进另一个数组的便捷方法。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> arr2 = [...arr1];</span><br></pre></td></tr></table></figure></p>
<p>扩展运算符也可以与解构赋值结合起来，用于生成数组。<br><figure class="highlight inform7"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">const <span class="comment">[first, ...rest]</span> = <span class="comment">[1, 2, 3, 4, 5]</span>;</span><br><span class="line">const <span class="comment">[...butLast, last]</span> = <span class="comment">[1, 2, 3, 4, 5]</span>; // 报错</span><br></pre></td></tr></table></figure></p>
<p>如果将扩展运算符用于数组赋值，只能放在参数的最后一位，否则会报错。</p>
<p>任何类似数组的对象，都可以用扩展运算符转为真正的数组。<br><figure class="highlight smali"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var nodeList =<span class="function"> document.querySelectorAll(</span>'div'<span class="function">)</span>;</span><br><span class="line">var<span class="instruction"> array </span>= <span class="keyword">[</span>...node<span class="class">List];</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，querySelectorAll方法返回的是一个nodeList对象，扩展运算符可以将其转为真正的数组。</p>
<p>扩展运算符内部调用的是数据结构的Iterable接口，因此只要具有Iterable接口的对象，都可以使用扩展运算符，比如Map结构。<br><figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="built_in">map</span> <span class="subst">=</span> <span class="literal">new</span> <span class="built_in">Map</span>(<span class="preprocessor">[</span></span><br><span class="line">  <span class="preprocessor">[</span><span class="number">1</span>, <span class="string">'one'</span><span class="preprocessor">]</span><span class="markup">,</span><br><span class="line">  </span><span class="preprocessor">[</span><span class="number">2</span>, <span class="string">'two'</span><span class="preprocessor">]</span><span class="markup">,</span><br><span class="line">  </span><span class="preprocessor">[</span><span class="number">3</span>, <span class="string">'three'</span><span class="preprocessor">]</span><span class="markup">,</span><br><span class="line">]);</span><br><span class="line"></span><br><span class="line">let arr = </span><span class="preprocessor">[</span><span class="attribute">...</span><span class="built_in">map</span><span class="built_in">.</span>keys()<span class="preprocessor">]</span><span class="markup">; // </span><span class="preprocessor">[</span><span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span><span class="preprocessor">]</span><span class="markup"></span></span><br></pre></td></tr></table></figure></p>
<p>Generator函数运行后，返回一个同时实现了Iterator和Iterable接口的对象，因此也可以使用扩展运算符。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> go = <span class="function"><span class="keyword">function</span>*(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">2</span>;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">3</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">[...go()] <span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，变量go是一个Generator函数，执行后返回的是一个Iterable对象，对这个对象执行扩展运算符，就会将内部遍历得到的值，转为一个数组。</p>
<h2 id="基本包装类型">基本包装类型</h2><p>为了便于操作基本类型值，ECMAScript提供了3个特殊的引用类型：Boolean、Number和String。实际上，每当读取一个基本类型值的时候，后台就会创建一个对应的基本包装类型的对象，从而让我们能够调用一些方法来操作这些数据。</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var <span class="variable">i =</span> <span class="number">1</span> .<span class="built_in">toString</span>(); //注意空格，否则会被当浮点数解析，然后抛错，还可以写为(<span class="number">1</span>).<span class="built_in">toString</span>()  <span class="number">1</span>..<span class="built_in">toString</span>()</span><br></pre></td></tr></table></figure>
<p>上例中实际执行了三步：1. 创建Number类型的一个实例 2. 在实例上调用指定方法 3. 销毁这个实例</p>
<p>引用类型与基本包装类型的主要区别就是对象的生存期。使用new操作符创建的引用类型的实例，在执行流离开当前作用域之前都一直保存在内存中。而自动创建的基本包装类型的对象，则只存在于一行代码的执行瞬间，然后立即被销毁。这意味着我们不能在运行时为基本类型值添加属性和方法<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> s1</span> = <span class="string">"some text"</span>;</span><br><span class="line">s1.color = <span class="string">"red"</span>;</span><br><span class="line">alert(s1.color); <span class="comment">//undefined</span></span><br></pre></td></tr></table></figure></p>
<p>在此,第二行代码试图为字符串 s1 添加一个 color 属性。但是,当第三行代码再次访问 s1 时, 其 color 属性不见了。问题的原因就是第二行创建的 String 对象在执行第三行代码时已经被销毁了。第三行代码又创建自己的 String 对象,而该对象没有 color 属性。</p>
<p>Object构造函数也会像工厂方法一样，根据传入值的类型返回相应基本包装类型的实例。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Object</span>(<span class="string">"some text"</span>);</span><br><span class="line">alert(obj <span class="keyword">instanceof</span> <span class="built_in">String</span>); <span class="comment">//true</span></span><br></pre></td></tr></table></figure></p>
<p>要注意的是，使用new调用基本包装类型的构造函数，与直接调用同名的转型函数是不一样的。 例如：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> value = <span class="string">"25"</span>;</span><br><span class="line"><span class="keyword">var</span> <span class="built_in">number</span> = <span class="built_in">Number</span>(value); <span class="comment">//转型函数</span></span><br><span class="line">alert(<span class="keyword">typeof</span> <span class="built_in">number</span>); <span class="comment">//"number"</span></span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="built_in">Number</span>(value); <span class="comment">//构造函数</span></span><br><span class="line">alert(<span class="keyword">typeof</span> obj); <span class="comment">//"object"</span></span><br></pre></td></tr></table></figure></p>
<h3 id="Boolean_类型">Boolean 类型</h3><p>Boolean 对象在 ECMAScript 中的用处不大,因为它经常会造成人们的误解。所以不推荐使用。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> falseObject = new <span class="type">Boolean</span>(<span class="literal">false</span>);</span><br><span class="line"><span class="keyword">var</span> <span class="literal">result</span> = falseObject &amp;&amp; <span class="literal">true</span>;</span><br><span class="line">alert(<span class="literal">result</span>); //这里返回的是<span class="literal">true</span> 布尔表达式中的所有对象都会被转换为<span class="literal">true</span></span><br></pre></td></tr></table></figure></p>
<p>基本类型与引用类型的布尔值还有两个区别。首先，typeof操作符对基本类型返回”boolean”，而对引用类型返回”object”。其次，由于Boolean对象是Boolean类型的实例，所以使用instanceof操作符测试Boolean对象会返回true，而测试基本类型的布尔值则返回false。</p>
<h3 id="Number_类型">Number 类型</h3><p>和Boolean类型类似，不推荐直接创建Number类型的实例，而应该使用基本类型。</p>
<p>toFixed()方法会按照指定的小数位返回数值的字符串表示。J如果数值本身包含的小数位比指定的还多，那么接近指定的最大小数位的值就会舍入<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">alert<span class="params">(<span class="params">(<span class="number">10</span>)</span>.toFixed<span class="params">(<span class="number">2</span>)</span>)</span>; <span class="comment">//"10.00"</span></span><br><span class="line">alert<span class="params">(<span class="params">(<span class="number">10.005</span>)</span>.toFixed<span class="params">(<span class="number">2</span>)</span>)</span>; <span class="comment">//"10.01"</span></span><br></pre></td></tr></table></figure></p>
<p>toFixed() 方法可以表示带有 0 到 20 个小数位的数值。但这只是标准实现的范围,有些浏览器也可能支持更多位数。</p>
<p>另外可用于格式化数值的方法是toExponential()，该方法返回以指数表示法（也称e表示法）表示的数值的字符串形式。与toFixed()一样，toExponential()也接收一个参数，而且该参数同样也是指定输出结果中的小数位数<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert<span class="params">(<span class="params">(<span class="number">10</span>)</span>.toExponential<span class="params">(<span class="number">1</span>)</span>)</span>; <span class="comment">//"1.0e+1"</span></span><br></pre></td></tr></table></figure></p>
<p>如果你想得到表示某个数值的最合适的格式,就应该使用 toPrecision() 方法。对于一个数值来说，toPrecision()方法可能会返回固定大小（fixed）格式，也可能返回指数（exponential）格式；具体规则是看哪种格式最合适。这个方法接收一个参数，即表示数值的所有数字的位数（不包括指数部分）。<br><figure class="highlight lisp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var num = <span class="number">99</span><span class="comment">;</span></span><br><span class="line">alert<span class="list">(<span class="keyword">num</span>.toPrecision<span class="list">(<span class="number">1</span>)</span>)</span><span class="comment">; //"1e+2"</span></span><br><span class="line">alert<span class="list">(<span class="keyword">num</span>.toPrecision<span class="list">(<span class="number">2</span>)</span>)</span><span class="comment">; //"99"</span></span><br><span class="line">alert<span class="list">(<span class="keyword">num</span>.toPrecision<span class="list">(<span class="number">3</span>)</span>)</span><span class="comment">; //"99.0"</span></span><br></pre></td></tr></table></figure></p>
<p>ES6提供了二进制和八进制数值的新的写法，分别用前缀0b和0o表示。<br><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="setting">0b111110111 =<span class="value">== <span class="number">503</span> // <span class="keyword">true</span></span></span></span><br><span class="line"><span class="setting">0o767 =<span class="value">== <span class="number">503</span> // <span class="keyword">true</span></span></span></span><br></pre></td></tr></table></figure></p>
<p>八进制不再允许使用前缀0表示，而改为使用前缀0o。</p>
<p>ES6在Number对象上，新提供了Number.isFinite()和Number.isNaN()两个方法，用来检查无穷（infinity）和NaN这两个特殊值。它们与传统的全局方法isFinite()和isNaN()的区别在于，传统方法先调用Number()将非数值的值转为数值，再进行判断，而这两个新方法只对数值有效，非数值一律返回false。</p>
<p>ES6将全局方法parseInt()和parseFloat()，移植到Number对象上面，行为完全保持不变。</p>
<p>Number.isInteger()用来判断一个值是否为整数。需要注意的是，在JavaScript内部，整数和浮点数是同样的储存方法，所以3和3.0被视为同一个值。<code>Number.isInteger(25.0) // true</code></p>
<p>JavaScript能够准确表示的整数范围在-2ˆ53 and 2ˆ53之间。ES6引入了<code>Number.MAX_SAFE_INTEGER</code>和<code>Number.MIN_SAFE_INTEGER</code>这两个常量，用来表示这个范围的上下限。Number.isSafeInteger()则是用来判断一个整数是否落在这个范围之内。</p>
<h3 id="String_类型">String 类型</h3><p>和Java中的String有点类似，String类型的方法只是返回一个新的字符串，不会改变原字符串。</p>
<p>String类型的每个实例都有一个length属性，表示字符串中包含多个字符。应该注意的是，即使字符串中包含双字节字符（不是占一个字节的ASCII字符），每个字符也仍然算一个字符。</p>
<p>两个用于访问字符串中特定字符的方法是：charAt()和 charCodeAt()。这两个方法都接收一个参数，即基于 0 的字符位置。其中，charAt()方法以单字符字符串的形式返回给定位置的那个字符</p>
<p>如果你想得到的不是字符而是字符编码，那么就要像下面这样使用charCodeAt()了。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable"><span class="keyword">var</span> stringValue</span> = <span class="string">"hello world"</span>; alert(stringValue.charCodeAt(<span class="number">1</span>)); <span class="comment">//输出"101"</span></span><br></pre></td></tr></table></figure></p>
<p>ECMAScript 5还定义了另一个访问个别字符的方法。在支持此方法的浏览器中，可以使用方括号加数字索引来访问字符串中的特定字符</p>
<p>concat()，用于将一或多个字符串拼接起来，返回拼接得到的新字符串。应用更多的还是加号操作符。</p>
<p>ECMAScript还提供了三个基于子字符串创建新字符串的方法：slice()、substr()和substring()。这三个方法都会返回被操作字符串的一个子字符串，而且也都接受一或两个参数。第一个参数指定子字符串的开始位置，第二个参数（在指定的情况下）表示子字符串到哪里结束。具体来说，slice()和substring()的第二个参数指定的是子字符串最后一个字符后面的位置。而 substr() 的第二个参数指定的则是返回的字符个数。如果没有给这些方法传递第二个参数，则将字符串的长度作为结束位置。与concat()方法一样，slice()、substr()和 substring()也不会修改字符串本身的值——它们只是返回一个基本类型的字符串值，对原始字符串没有任何影响。</p>
<p>在传递给这些方法的参数是负值的情况下，它们的行为就不尽相同了。其中，slice()方法会将传入的负值与字符串的长度相加，substr()方法将负的第一个参数加上字符串的长度，而将负的第二个参数转换为0。最后，substring()方法会把所有负值参数都转换为0<br><figure class="highlight lisp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var stringValue = <span class="string">"hello world"</span><span class="comment">;</span></span><br><span class="line">alert<span class="list">(<span class="keyword">stringValue</span>.slice<span class="list">(<span class="keyword">-3</span>)</span>)</span><span class="comment">; //"rld" slice(8)</span></span><br><span class="line">alert<span class="list">(<span class="keyword">stringValue</span>.substring<span class="list">(<span class="keyword">-3</span>)</span>)</span><span class="comment">; //"hello world" substring(0)</span></span><br><span class="line">alert<span class="list">(<span class="keyword">stringValue</span>.substr<span class="list">(<span class="keyword">-3</span>)</span>)</span><span class="comment">; //"rld" substr(8)</span></span><br><span class="line">alert<span class="list">(<span class="keyword">stringValue</span>.slice<span class="list">(<span class="number">3</span>, <span class="number">-4</span>)</span>)</span><span class="comment">; //"lo w" slice(3, 7)</span></span><br><span class="line">alert<span class="list">(<span class="keyword">stringValue</span>.substring<span class="list">(<span class="number">3</span>, <span class="number">-4</span>)</span>)</span><span class="comment">; //"hel" substring(3,0) 而由于这个方法会将较小的数作为开始位置,将较大的数作为结束位置, 因此最终相当于调用了 substring(0,3)</span></span><br><span class="line">alert<span class="list">(<span class="keyword">stringValue</span>.substr<span class="list">(<span class="number">3</span>, <span class="number">-4</span>)</span>)</span><span class="comment">; //""(空字符串) substr(3,0)</span></span><br></pre></td></tr></table></figure></p>
<p>有两个可以从字符串中查找子字符串的方法：indexOf()和lastIndexOf()。这两个方法都是从一个字符串中搜索给定的子字符串，然后返子字符串的位置（如果没有找到该子字符串，则返回-1）。这两个方法都可以接收可选的第二个参数，表示从字符串中的哪个位置开始搜索</p>
<p>trim()方法。这个方法会创建一个字符串的副本，删除前置及后缀的所有空格，然后返回结果。Firefox 3.5+、Safari 5+和Chrome 8+还支持非标准的trimLeft()和trimRight()方法，分别用于删除字符串开头和末尾的空格。</p>
<p>接下来我们要介绍的是一组与大小写转换有关的方法。ECMAScript 中涉及字符串大小写转换的方法有4个：toLowerCase()、toLocaleLowerCase()、toUpperCase()和toLocaleUpperCase()。</p>
<p>String类型定义了几个用于在字符串中匹配模式的方法。第一个方法就是match()，在字符串上调用这个方法，本质上与调用 RegExp 的 exec()方法相同。match()方法只接受一个参数，要么是一个正则表达式，要么是一个RegExp对象</p>
<p>另一个用于查找模式的方法是search()。这个方法的唯一参数与match()方法的参数相同：由字符串或 RegExp 对象指定的一个正则表达式。search()方法返回字符串中第一个匹配项的索引；如果没有找到匹配项，则返回-1。</p>
<p>为了简化替换子字符串的操作，ECMAScript提供了replace()方法。这个方法接受两个参数：第一个参数可以是一个 RegExp 对象或者一个字符串（这个字符串不会被转换成正则表达式），第二个参数可以是一个字符串或者一个函数。如果第一个参数是字符串，那么只会替换第一个子字符串。要想替换所有子字符串，唯一的办法就是提供一个正则表达式，而且要指定全局（g）标志</p>
<p>如果第二个参数是字符串,那么还可以使用一些特殊的字符序列,将正则表达式操作得到的值插入到结果字符串中。下表列出了ECMAScript提供的这些特殊的字符序列。</p>
<table>
<thead>
<tr>
<th>字符序列</th>
<th>替换文本</th>
</tr>
</thead>
<tbody>
<tr>
<td>$$</td>
<td>$</td>
</tr>
<tr>
<td>$&amp;</td>
<td>匹配整个模式的子字符串。与 RegExp.lastMatch 的值相同</td>
</tr>
<tr>
<td>$’</td>
<td>匹配的子字符串之前的子字符串。与 RegExp.leftContext 的值相同</td>
</tr>
<tr>
<td>$`</td>
<td>匹配的子字符串之后的子字符串。与 RegExp.rightContext 的值相同</td>
</tr>
<tr>
<td>$n</td>
<td>匹配第n个捕获组的子字符串,其中n等于0~9。例如, $1 是匹配第一个捕获组的子字符串, $2 是匹配第二个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串</td>
</tr>
<tr>
<td>$nn</td>
<td>匹配第nn个捕获组的子字符串,其中nn等于01~99。例如, $01 是匹配第一个捕获组的子字符串, $02是匹配第二个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串</td>
</tr>
</tbody>
</table>
<p>replace()方法的第二个参数也可以是一个函数。在只有一个匹配项（即与模式匹配的字符串）的情况下，会向这个函数传递3个参数：模式的匹配项、模式匹配项在字符串中的位置和原始字符串。在正则表达式中定义了多个捕获组的情况下，传递给函数的参数依次是模式的匹配项、第一个捕获组的匹配项、第二个捕获组的匹配项……，但最后两个参数仍然分别是模式的匹配项在字符串中的位置和原始字符串。这个函数应该返回一个字符串，表示应该被替换的匹配项使用函数作为 replace()方法的第二个参数可以实现更加精细的替换操作</p>
<p>最后一个与模式匹配有关的方法是split()，这个方法可以基于指定的分隔符将一个字符串分割成多个子字符串，并将结果放在一个数组中。分隔符可以是字符串，也可以是一个RegExp对象（这个方法不会将字符串看成正则表达式）。split()方法可以接受可选的第二个参数，用于指定数组的大小，以便确保返回的数组不会超过既定大小。</p>
<p>对 split() 中正则表达式的支持因浏览器而异。尽管对于简单的模式没有什么差别,但对于未发现匹配项以及带有捕获组的模式,匹配的行为就不大相同了。以下是几种常见的差别。</p>
<ul>
<li>IE8 及之前版本会忽略捕获组。ECMA-262 规定应该把捕获组拼接到结果数组中。IE9 能正确地在结果中包含捕获组。</li>
<li>Firefox 3.6 及之前版本在捕获组未找到匹配项时,会在结果数组中包含空字符串;ECMA-262 规定没有匹配项的捕获组在结果数组中应该用 undefined 表示。</li>
</ul>
<p>ES6将match()、replace()、search()和split()这4个方法，在语言内部全部调用RegExp的实例方法，从而做到所有与正则相关的方法，全都定义在RegExp对象上。</p>
<ul>
<li>String.prototype.match 调用 RegExp.prototype[Symbol.match]</li>
<li>String.prototype.replace 调用 RegExp.prototype[Symbol.replace]</li>
<li>String.prototype.search 调用 RegExp.prototype[Symbol.search]</li>
<li>String.prototype.split 调用 RegExp.prototype[Symbol.split]</li>
</ul>
<p>与操作字符串有关的最后一个方法是localeCompare()，这个方法比较两个字符串，并返回下列值中的一个：</p>
<ul>
<li>如果字符串在字母表中应该排在字符串参数之前，则返回一个负数（大多数情况下是-1，具体的值要视实现而定）；</li>
<li>如果字符串等于字符串参数，则返回0；</li>
<li>如果字符串在字母表中应该排在字符串参数之后，则返回一个正数（大多数情况下是1，具体的值同样要视实现而定）。</li>
</ul>
<p>另外，String 构造函数本身还有一个静态方法：fromCharCode()。这个方法的任务是接收一或多个字符编码，然后将它们转换成一个字符串</p>
<p>一些被浏览器扩展的方法，应该尽量不使用这些方法,因为它们创建的标记通常无法表达语义。</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>输出结果</th>
</tr>
</thead>
<tbody>
<tr>
<td>anchor(name)</td>
<td><code>&lt;a name= &quot;name&quot;&gt;string&lt;/a&gt;</code></td>
</tr>
<tr>
<td>big()</td>
<td><code>&lt;big&gt;string&lt;/big&gt;</code></td>
</tr>
<tr>
<td>bold()</td>
<td><code>&lt;b&gt;string&lt;/b&gt;</code></td>
</tr>
<tr>
<td>fixed()</td>
<td><code>&lt;tt&gt;string&lt;/tt&gt;</code></td>
</tr>
<tr>
<td>fontcolor(color)</td>
<td><code>&lt;font color=&quot;color&quot;&gt;string&lt;/font&gt;</code></td>
</tr>
<tr>
<td>fontsize(size)</td>
<td><code>&lt;font size=&quot;size&quot;&gt;string&lt;/font&gt;</code></td>
</tr>
<tr>
<td>italics()</td>
<td><code>&lt;i&gt;string&lt;/i&gt;</code></td>
</tr>
<tr>
<td>link(url)</td>
<td><code>&lt;a href=&quot;url&quot;&gt;string&lt;/a&gt;</code></td>
</tr>
<tr>
<td>small()</td>
<td><code>&lt;small&gt;string&lt;/small&gt;</code></td>
</tr>
<tr>
<td>strike()</td>
<td><code>&lt;strike&gt;string&lt;/strike&gt;</code></td>
</tr>
<tr>
<td>sub()</td>
<td><code>&lt;sub&gt;string&lt;/sub&gt;</code></td>
</tr>
<tr>
<td>sup()</td>
<td><code>&lt;sup&gt;string&lt;/sup&gt;</code></td>
</tr>
</tbody>
</table>
<p>ECMAScript6中对String进行了扩展。</p>
<p>对于Unicode字符，之前<code>\u20BB7</code>会被解析为<code>\u20BB+7</code>。由于\u20BB是一个不可打印字符，所以只会显示一个空格，后面跟着一个7。ES6对这一点做出了改进，只要将码点放入大括号，就能正确解读该字符。<code>\u{20BB7}</code></p>
<p>ES6提供了String.fromCodePoint方法，可以识别码点大于0xFFFF（辅助平面）的字符，弥补了String.fromCharCode方法的不足。在作用上，正好与codePointAt方法相反。<br><figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">String.fromCharCode(0x20BB7);// </span><span class="string">"ஷ"</span></span><br><span class="line"><span class="keyword">String.fromCodePoint(0x20BB7);// </span><span class="string">"𠮷"</span></span><br></pre></td></tr></table></figure></p>
<p>注意，fromCodePoint方法定义在String对象上，而codePointAt方法定义在字符串的实例对象上。</p>
<p>ES6提供了String.codePointAt方法，能够正确处理4个字节储存的字符，返回一个字符的码点。<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var s = <span class="string">"𠮷a"</span>;</span><br><span class="line"></span><br><span class="line">s.codePointAt<span class="params">(<span class="number">0</span>)</span> <span class="comment">// 134071</span></span><br><span class="line">s.codePointAt<span class="params">(<span class="number">1</span>)</span> <span class="comment">// 57271</span></span><br><span class="line"></span><br><span class="line">s.charCodeAt<span class="params">(<span class="number">0</span>)</span> <span class="comment">// 55362</span></span><br><span class="line">s.charCodeAt<span class="params">(<span class="number">1</span>)</span> <span class="comment">// 57271</span></span><br><span class="line">s.charCodeAt<span class="params">(<span class="number">2</span>)</span> <span class="comment">// 97</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，汉字“𠮷”的码点是0x20BB7，UTF-16编码为0xD842 0xDFB7（十进制为55362 57271），需要4个字节储存。对于这种4个字节的字符，JavaScript不能正确处理，字符串长度会误判为2，而且charAt方法无法读取字符，charCodeAt方法只能分别返回前两个字节和后两个字节的值。</p>
<p>codePointAt方法的参数，是字符在字符串中的位置（从0开始）。上面代码中，JavaScript将“𠮷a”视为三个字符，codePointAt方法在第一个字符上，正确地识别了“𠮷”，返回了它的十进制码点134071（即十六进制的20BB7）。在第二个字符（即“𠮷”的后两个字节）和第三个字符“a”上，codePointAt方法的结果与charCodeAt方法相同。</p>
<p>ES5对字符串对象提供charAt方法，返回字符串给定位置的字符。该方法不能识别码点大于0xFFFF的字符。</p>
<p>ES7提供了字符串实例的at方法，可以识别Unicode编号大于0xFFFF的字符，返回正确的字符。Chrome浏览器已经支持该方法。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'𠮷'</span>.<span class="function"><span class="title">charAt</span><span class="params">(<span class="number">0</span>)</span></span> <span class="comment">// "\uD842"</span></span><br><span class="line"></span><br><span class="line"><span class="string">'abc'</span>.<span class="function"><span class="title">at</span><span class="params">(<span class="number">0</span>)</span></span> <span class="comment">// "a"</span></span><br><span class="line"><span class="string">'𠮷'</span>.<span class="function"><span class="title">at</span><span class="params">(<span class="number">0</span>)</span></span> <span class="comment">// "𠮷"</span></span><br></pre></td></tr></table></figure></p>
<p>为了表示语调和重音符号，Unicode提供了两种方法。一种是直接提供带重音符号的字符，比如Ǒ（\u01D1）。另一种是提供合成符号（combining character），即原字符与重音符号的合成，两个字符合成一个字符，比如O（\u004F）和ˇ（\u030C）合成Ǒ（\u004F\u030C）。</p>
<p>这两种表示方法，在视觉和语义上都等价，但是JavaScript不能识别。<br><figure class="highlight mel"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'\u01D1'</span>.<span class="keyword">normalize</span>() === <span class="string">'\u004F\u030C'</span>.<span class="keyword">normalize</span>(); <span class="comment">// true</span></span><br></pre></td></tr></table></figure></p>
<p>normalize方法可以接受四个参数。</p>
<ul>
<li>NFC，默认参数，表示“标准等价合成”（Normalization Form Canonical Composition），返回多个简单字符的合成字符。所谓“标准等价”指的是视觉和语义上的等价。</li>
<li>NFD，表示“标准等价分解”（Normalization Form Canonical Decomposition），即在标准等价的前提下，返回合成字符分解的多个简单字符。</li>
<li>NFKC，表示“兼容等价合成”（Normalization Form Compatibility Composition），返回合成字符。所谓“兼容等价”指的是语义上存在等价，但视觉上不等价，比如“囍”和“喜喜”。</li>
<li>NFKD，表示“兼容等价分解”（Normalization Form Compatibility Decomposition），即在兼容等价的前提下，返回合成字符分解的多个简单字符。</li>
</ul>
<p>不过，normalize方法目前不能识别三个或三个以上字符的合成。这种情况下，还是只能使用正则表达式，通过Unicode编号区间判断。</p>
<p>传统上，JavaScript只有indexOf方法，可以用来确定一个字符串是否包含在另一个字符串中。ES6又提供了三种新方法。</p>
<ul>
<li>includes()：返回布尔值，表示是否找到了参数字符串。</li>
<li>startsWith()：返回布尔值，表示参数字符串是否在源字符串的头部。</li>
<li>endsWith()：返回布尔值，表示参数字符串是否在源字符串的尾部。</li>
</ul>
<p>这三个方法都支持第二个参数，表示开始搜索的位置。使用第二个参数n时，endsWith的行为与其他两个方法有所不同。它针对前n个字符，而其他两个方法针对从第n个位置直到字符串结束。</p>
<p>repeat()返回一个新字符串，表示将原字符串重复n次。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"hello"</span>.<span class="function"><span class="title">repeat</span><span class="params">(<span class="number">3</span>)</span></span> <span class="comment">// "hellohellohello"</span></span><br></pre></td></tr></table></figure></p>
<p>模板字符串（template string）是增强版的字符串，用反引号（`）标识。它可以当作普通字符串使用，也可以用来定义多行字符串，或者在字符串中嵌入变量。模板字符串中嵌入变量，需要将变量名写在<code>${}</code>之中。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 普通字符串</span></span><br><span class="line">`<span class="keyword">In</span> JavaScript '\<span class="keyword">n</span>' is a <span class="keyword">line</span>-feed.`</span><br><span class="line"><span class="comment">// 多行字符串</span></span><br><span class="line">`<span class="keyword">In</span> JavaScript this is</span><br><span class="line"> not legal.`</span><br><span class="line">console.<span class="literal">log</span>(`string text <span class="keyword">line</span> 1</span><br><span class="line">string text <span class="keyword">line</span> 2`);</span><br><span class="line"><span class="comment">// 字符串中嵌入变量</span></span><br><span class="line"><span class="keyword">var</span> name = <span class="string">"Bob"</span>, time = <span class="string">"today"</span>;</span><br><span class="line">console.<span class="literal">log</span>(`\`Hello <span class="label">$&#123;name&#125;</span>, how are you <span class="label">$&#123;time&#125;</span>?\`</span><br><span class="line">$&#123;'Mr. ' + name&#125;</span><br><span class="line">`);</span><br></pre></td></tr></table></figure>
<p>如果在模板字符串中需要使用反引号，则前面要用反斜杠转义。</p>
<p>大括号内部可以放入任意的JavaScript表达式，可以进行运算，以及引用对象属性。模板字符串之中还能调用函数</p>
<p>如果使用模板字符串表示多行字符串，所有的空格和缩进都会被保留在输出之中。</p>
<p>如果大括号中的值不是字符串，将按照一般的规则转为字符串。比如，大括号中是一个对象，将默认调用对象的toString方法。</p>
<p>如果模板字符串中的变量没有声明，将报错。</p>
<p>标签模板</p>
<p>模板字符串的功能，不仅仅是上面这些。它可以紧跟在一个函数名后面，该函数将被调用来处理这个模板字符串。这被称为“标签模板”功能（tagged template）。<br><figure class="highlight autohotkey"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var <span class="literal">a</span> = <span class="number">5</span><span class="comment">;</span></span><br><span class="line">var b = <span class="number">10</span><span class="comment">;</span></span><br><span class="line">tag<span class="escape">`H</span>ello $&#123; <span class="literal">a</span> + b &#125; world $&#123; <span class="literal">a</span> * b &#125;<span class="escape">`;</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，模板字符串前面有一个标识名tag，它是一个函数。整个表达式的返回值，就是tag函数处理模板字符串后的返回值。</p>
<p>函数tag依次会接收到多个参数。<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">tag</span><span class="params">(stringArr, value1, value2)</span></span>&#123; <span class="comment">// ...  &#125;</span></span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">tag</span><span class="params">(stringArr, <span class="rest_arg">...values</span>)</span></span>&#123; <span class="comment">// ...  &#125;</span></span><br></pre></td></tr></table></figure></p>
<p>tag函数的第一个参数是一个数组，该数组的成员是模板字符串中那些没有变量替换的部分，也就是说，变量替换只发生在数组的第一个成员与第二个成员之间、第二个成员与第三个成员之间，以此类推。</p>
<p>tag函数的其他参数，都是模板字符串各个变量被替换后的值。由于本例中，模板字符串含有两个变量，因此tag会接受到value1和value2两个参数。</p>
<p>tag函数所有参数的实际值如下。</p>
<ul>
<li>第一个参数：[‘Hello ‘, ‘ world ‘, ‘’]</li>
<li>第二个参数: 15</li>
<li>第三个参数：50</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">5</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">tag</span>(<span class="params">s, v1, v2</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(s[<span class="number">0</span>]);</span><br><span class="line">  <span class="built_in">console</span>.log(s[<span class="number">1</span>]);</span><br><span class="line">  <span class="built_in">console</span>.log(s[<span class="number">2</span>]);</span><br><span class="line">  <span class="built_in">console</span>.log(v1);</span><br><span class="line">  <span class="built_in">console</span>.log(v2);</span><br><span class="line">  <span class="keyword">return</span> <span class="string">"OK"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">tag<span class="string">`Hello <span class="subst">$&#123; a + b &#125;</span> world <span class="subst">$&#123; a * b&#125;</span>`</span>;</span><br><span class="line"><span class="comment">// "Hello "</span></span><br><span class="line"><span class="comment">// " world "</span></span><br><span class="line"><span class="comment">// ""</span></span><br><span class="line"><span class="comment">// 15</span></span><br><span class="line"><span class="comment">// 50</span></span><br><span class="line"><span class="comment">// "OK"</span></span><br></pre></td></tr></table></figure>
<p>“标签模板”的一个重要应用，就是过滤HTML字符串，防止用户输入恶意内容。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> message =</span><br><span class="line">  SaferHTML<span class="string">`&lt;p&gt;<span class="subst">$&#123;sender&#125;</span> has sent you a message.&lt;/p&gt;`</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">SaferHTML</span>(<span class="params">templateData</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> s = templateData[<span class="number">0</span>];</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="built_in">arguments</span>.length; i++) &#123;</span><br><span class="line">    <span class="keyword">var</span> arg = <span class="built_in">String</span>(<span class="built_in">arguments</span>[i]);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Escape special characters in the substitution.</span></span><br><span class="line">    s += arg.replace(<span class="regexp">/&amp;/g</span>, <span class="string">"&amp;amp;"</span>)</span><br><span class="line">            .replace(<span class="regexp">/&lt;/g</span>, <span class="string">"&amp;lt;"</span>)</span><br><span class="line">            .replace(<span class="regexp">/&gt;/g</span>, <span class="string">"&amp;gt;"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Don't escape special characters in the template.</span></span><br><span class="line">    s += templateData[i];</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> s;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>标签模板的另一个应用，就是多语言转换（国际化处理）。</p>
<p>模板字符串本身并不能取代Mustache之类的模板库，因为没有条件判断和循环处理功能，但是通过标签函数，你可以自己添加这些功能。</p>
<p>模板处理函数的第一个参数（模板字符串数组），还有一个raw属性。<br><figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">tag</span>`First <span class="built_in">line</span>\nSecond <span class="built_in">line</span>`</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">tag</span><span class="params">(strings)</span> &#123;</span></span><br><span class="line">  console.<span class="built_in">log</span>(strings.raw[<span class="number">0</span>]);</span><br><span class="line">  // <span class="string">"First line\\nSecond line"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，tag函数的第一个参数strings，有一个raw属性，也指向一个数组。该数组的成员与strings数组完全一致。比如，strings数组是<code>[&quot;First line\nSecond line&quot;]</code>，那么strings.raw数组就是<code>[&quot;First line\\nSecond line&quot;]</code>。两者唯一的区别，就是字符串里面的斜杠都被转义了。比如，strings.raw数组会将<code>\n</code>视为<code>\</code>和<code>n</code>两个字符，而不是换行符。这是为了方便取得转义之前的原始模板而设计的。</p>
<p>ES6还为原生的String对象，提供了一个raw方法。String.raw方法，往往用来充当模板字符串的处理函数，返回一个斜杠都被转义（即斜杠前面再加一个斜杠）的字符串，对应于替换变量后的模板字符串。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>.raw<span class="string">`Hi\n<span class="subst">$&#123;2+3&#125;</span>!`</span>;</span><br><span class="line"><span class="comment">// "Hi\\n5!"</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">String</span>.raw<span class="string">`Hi\u000A!`</span>;</span><br><span class="line"><span class="comment">// 'Hi\\u000A!'</span></span><br></pre></td></tr></table></figure>
<p>String.raw方法可以作为处理模板字符串的基本方法，它会将所有变量替换，而且对斜杠进行转义，方便下一步作为字符串来使用。</p>
<p>String.raw方法也可以作为正常的函数使用。这时，它的第一个参数，应该是一个具有raw属性的对象，且raw属性的值应该是一个数组。</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">String</span><span class="class">.raw</span>(&#123; <span class="attribute">raw</span>: <span class="string">'test'</span> &#125;, <span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>); <span class="comment">// 't0e1s2t'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 等同于</span></span><br><span class="line"><span class="tag">String</span><span class="class">.raw</span>(&#123; <span class="attribute">raw</span>: [<span class="string">'t'</span>,<span class="string">'e'</span>,<span class="string">'s'</span>,<span class="string">'t'</span>] &#125;, <span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>);</span><br></pre></td></tr></table></figure>
<h2 id="单体内置对象">单体内置对象</h2><h3 id="Global对象">Global对象</h3><p>Global（全局）对象可以说是ECMAScript中最特别的一个对象了，因为不管你从什么角度上看，这个对象都是不存在的。ECMAScript中的Global对象在某种意义上是作为一个终极的“兜底儿对象”来定义的。换句话说，不属于任何其他对象的属性和方法，最终都是它的属性和方法。事实上，没有全局变量或全局函数；所有在全局作用域中定义的属性和函数，都是Global对象的属性。诸如 isNaN() 、 isFinite() 、 parseInt() 以及 parseFloat() ,实际上全都是 Global 对象的方法。</p>
<ul>
<li><p>URI 编码方法<br>  对象的 encodeURI()和 encodeURIComponent()方法可以对 URI（Uniform Resource Identifiers，通用资源标识符）进行编码，以便发送给浏览器。有效的 URI 中不能包含某些字符，例如空格。而这两个URI编码方法就可以对URI进行编码，它们用特殊的UTF-8编码替换所有无效的字符，从而让浏览器能够接受和理解。 其中，encodeURI()主要用于整个URI（例如，<code>http://www.wrox.com/illegal value.htm</code>），而 encodeURIComponent()主要用于对URI中的某一段（例如前面URI中的illegal value.htm）进行编码。它们的主要区别在于，encodeURI()不会对本身属于 URI 的特殊字符进行编码，例如冒号、正斜杠、问号和井字号；而encodeURIComponent()则会对它发现的任何非标准字符进行编码。</p>
<p>  一般来说，我们使用 encodeURIComponent()方法的时候要比使用encodeURI()更多，因为在实践中更常见的是对查询字符串参数而不是对基础 URI进行编码。</p>
<p>  与 encodeURI()和 encodeURIComponent()方法对应的两个方法分别是 decodeURI()和decodeURIComponent()</p>
</li>
<li><p>eval()方法<br>  现在，我们介绍最后一个——大概也是整个ECMAScript语言中最强大的一个方法：eval()。eval()方法就像是一个完整的ECMAScript解析器，它只接受一个参数，即要执行的ECMAScript（或JavaScript）字符串。看例子： eval(“alert(‘hi’)”); 这行代码的作用等价于代码： alert(“hi”);</p>
<p>  当解析器发现代码中调用eval()方法时，它会将传入的参数当作实际的ECMAScript语句来解析，然后把执行结果插入到原位置。通过 eval() 执行的代码可以引用在包<br>含环境中定义的变量 <code>var msg = &quot;hello world&quot;; eval(&quot;alert(msg)&quot;);</code></p>
<p>  在eval()中创建的任何变量或函数都不会被提升，因为在解析代码的时候，它们被包含在一个字符串中；它们只在eval()执行的时候创建。 严格模式下，在外部访问不到eval()中创建的任何变量或函数，在严格模式下,为 eval 赋值也会导致错误</p>
</li>
<li><p>Global 对象的属性<br>  特殊的值undefined、NaN以及Infinity都是Global对象的属性。此外，所有原生引用类型的构造函数，像Object和Function，也都是Global对象的属性。下表列出了Global对象的所有属性。</p>
</li>
</ul>
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>undefined</td>
<td>特殊值 undefined</td>
</tr>
<tr>
<td>NaN</td>
<td>特殊值 NaN</td>
</tr>
<tr>
<td>Infinity</td>
<td>特殊值 Infinity</td>
</tr>
<tr>
<td>Date</td>
<td>构造函数 Date</td>
</tr>
<tr>
<td>RegExp</td>
<td>构造函数 RegExp</td>
</tr>
<tr>
<td>Error</td>
<td>构造函数 Error</td>
</tr>
<tr>
<td>Object</td>
<td>构造函数 Object</td>
</tr>
<tr>
<td>Array</td>
<td>构造函数 Array</td>
</tr>
<tr>
<td>Function</td>
<td>构造函数 Function</td>
</tr>
<tr>
<td>Boolean</td>
<td>构造函数 Boolean</td>
</tr>
<tr>
<td>String</td>
<td>构造函数 String</td>
</tr>
<tr>
<td>Number</td>
<td>构造函数 Number</td>
</tr>
<tr>
<td>EvalError</td>
<td>构造函数 EvalError</td>
</tr>
<tr>
<td>RangeError</td>
<td>构造函数 RangeError</td>
</tr>
<tr>
<td>ReferenceError</td>
<td>构造函数 ReferenceError</td>
</tr>
<tr>
<td>SyntaxError</td>
<td>构造函数 SyntaxError</td>
</tr>
<tr>
<td>TypeError</td>
<td>构造函数 TypeError</td>
</tr>
<tr>
<td>URIError</td>
<td>构造函数 URIError</td>
</tr>
</tbody>
</table>
<p>ECMAScript 5明确禁止给undefined、NaN和Infinity赋值，这样做即使在非严格模式下也会导致错误。</p>
<ul>
<li>window 对象<br>  ECMAScript 虽然没有指出如何直接访问 Global 对象，但 Web 浏览器都是将这个全局对象作为window对象的一部分加以实现的。因此，在全局作用域中声明的所有变量和函数，就都成为了window对象的属性。</li>
</ul>
<h3 id="Math_对象">Math 对象</h3><p>Math对象包含的属性大都是数学计算中可能会用到的一些特殊值。下表列出了这些属性。</p>
<ul>
<li>Math 对象的属性</li>
</ul>
<table>
<thead>
<tr>
<th>属 性</th>
<th>说 明</th>
</tr>
</thead>
<tbody>
<tr>
<td>Math.E</td>
<td>自然对数的底数，即常量e的值</td>
</tr>
<tr>
<td>Math.LN10</td>
<td>10的自然对数</td>
</tr>
<tr>
<td>Math.LN2</td>
<td>2的自然对数</td>
</tr>
<tr>
<td>Math.LOG2E</td>
<td>以2为底e的对数</td>
</tr>
<tr>
<td>Math.LOG10E</td>
<td>以10为底e的对数</td>
</tr>
<tr>
<td>Math.PI</td>
<td>π的值</td>
</tr>
<tr>
<td>Math.SQRT1_2</td>
<td>1/2的平方根（即2的平方根的倒数）</td>
</tr>
<tr>
<td>Math.SQRT2</td>
<td>2的平方根</td>
</tr>
</tbody>
</table>
<ul>
<li><p>min() 和 max() 方法<br>  这两个方法都可以接收任意多个数值参数，要查找数组中的最大值可以使用apply方法。</p>
  <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.min(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>);</span><br><span class="line"><span class="keyword">var</span> values = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>];</span><br><span class="line"><span class="keyword">var</span> max = <span class="built_in">Math</span>.max.apply(<span class="built_in">Math</span>, values);</span><br></pre></td></tr></table></figure>
</li>
<li><p>舍入方法</p>
<ul>
<li>Math.ceil()执行向上舍入，即它总是将数值向上舍入为最接近的整数；</li>
<li>Math.floor()执行向下舍入，即它总是将数值向下舍入为最接近的整数；</li>
<li>Math.round()执行标准舍入，即它总是将数值四舍五入为最接近的整数</li>
</ul>
</li>
<li><p>random() 方法<br>  Math.random() 方法返回大于等于 0 小于 1 的一个随机数。套用下面的公式，就可以利用Math.random()从某个整数范围内随机选择一个值。 <code>值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)</code></p>
</li>
<li><p>其他方法</p>
</li>
</ul>
<table>
<thead>
<tr>
<th>方 法</th>
<th>说 明</th>
</tr>
</thead>
<tbody>
<tr>
<td>Math.abs(num)</td>
<td>返回num 的绝对值</td>
</tr>
<tr>
<td>Math.exp(num)</td>
<td>返回Math.E 的num 次幂</td>
</tr>
<tr>
<td>Math.log(num)</td>
<td>返回num 的自然对数</td>
</tr>
<tr>
<td>Math.pow(num,power)</td>
<td>返回num 的power 次幂</td>
</tr>
<tr>
<td>Math.sqrt(num)</td>
<td>返回num 的平方根</td>
</tr>
<tr>
<td>Math.acos(x)</td>
<td>返回x 的反余弦值</td>
</tr>
<tr>
<td>Math.asin(x)</td>
<td>返回x 的反正弦值</td>
</tr>
<tr>
<td>Math.atan(x)</td>
<td>返回x 的反正切值</td>
</tr>
<tr>
<td>Math.atan2(y,x)</td>
<td>返回y/x 的反正切值</td>
</tr>
<tr>
<td>Math.cos(x)</td>
<td>返回x 的余弦值</td>
</tr>
<tr>
<td>Math.sin(x)</td>
<td>返回x 的正弦值</td>
</tr>
<tr>
<td>Math.tan(x)</td>
<td>返回x 的正切值</td>
</tr>
</tbody>
</table>
<ul>
<li><p>ES6新增方法</p>
<ul>
<li>Math.trunc(num)：去除一个数的小数部分，返回整数部分，对于空值和无法截取整数的值，返回NaN</li>
<li>Math.sign(num)：判断一个数到底是正数、负数、还是零。参数为正数，返回+1； 参数为负数，返回-1； 参数为0，返回0； 参数为-0，返回-0; 其他值，返回NaN。</li>
<li>Math.cbrt(num)：计算一个数的立方根</li>
<li>Math.clz32(num)：返回一个数的32位无符号整数二进制形式表示有多少个前导0。对于小数，只考虑整数部分，对于其他值，先转为数值，再计算</li>
<li>Math.imul(num1,num2)：回两个数以32位带符号整数形式相乘的结果，返回的也是一个32位的带符号整数。多数情况和<code>(a * b)|0</code>效果相同，但JavaScript对于超过2的53次方的值无法精确表示，该方法可以得到正确值</li>
<li>Math.fround(num)：Math.fround方法返回一个数的单精度浮点数形式。对于整数来说，Math.fround方法返回结果不会有任何不同，区别主要是那些无法用64个二进制位精确表示的小数。这时，Math.fround方法会返回最接近这个小数的单精度浮点数。</li>
<li>Math.hypot()：返回所有参数的平方和的平方根，如果参数不是数值，Math.hypot方法会将其转为数值。只要有一个参数无法转为数值，就会返回NaN</li>
<li>Math.expm1()：返回Math.exp(x) - 1</li>
<li>Math.log1p()：返回1 + x的自然对数。如果x小于-1，返回NaN</li>
<li>Math.log10()：返回以10为底的x的对数。如果x小于0，则返回NaN</li>
<li>Math.log2()：返回以2为底的x的对数。如果x小于0，则返回NaN</li>
<li>Math.sinh(x)：返回x的双曲正弦（hyperbolic sine）</li>
<li>Math.cosh(x)：返回x的双曲余弦（hyperbolic cosine）</li>
<li>Math.tanh(x)：返回x的双曲正切（hyperbolic tangent）</li>
<li>Math.asinh(x)：返回x的反双曲正弦（inverse hyperbolic sine）</li>
<li>Math.acosh(x)：返回x的反双曲余弦（inverse hyperbolic cosine）</li>
<li>Math.atanh(x)：返回x的反双曲正切（inverse hyperbolic tangent）</li>
</ul>
</li>
</ul>
<h2 id="键集合类型">键集合类型</h2><h3 id="Map_类型">Map 类型</h3><h4 id="基本用法">基本用法</h4><p>JavaScript的对象（Object），本质上是键值对的集合（Hash结构），但是只能用字符串当作键。这给它的使用带来了很大的限制。</p>
<figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">var</span> <span class="typedef"><span class="keyword">data</span> = <span class="container">&#123;&#125;</span>;</span></span><br><span class="line"><span class="title">var</span> element = document.getElementById(<span class="string">"myDiv"</span>);</span><br><span class="line"></span><br><span class="line"><span class="typedef"><span class="keyword">data</span>[element] = metadata;</span></span><br><span class="line"><span class="typedef"><span class="keyword">data</span>["[<span class="type">Object</span> <span class="type">HTMLDivElement</span>]"] // metadata</span></span><br></pre></td></tr></table></figure>
<p>上面代码原意是将一个DOM节点作为对象data的键，但是由于对象只接受字符串作为键名，所以element被自动转为字符串<code>[Object HTMLDivElement]</code>。</p>
<p>为了解决这个问题，ES6提供了Map数据结构。它类似于对象，也是键值对的集合，但是“键”的范围不限于字符串，各种类型的值（包括对象）都可以当作键。也就是说，Object结构提供了“字符串—值”的对应，Map结构提供了“值—值”的对应，是一种更完善的Hash结构实现。如果你需要“键值对”的数据结构，Map比Object更合适。</p>
<p>作为构造函数，Map可以接受一个数组作为参数。该数组的成员是一个个表示键值对的数组。</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var <span class="built_in">map</span> = <span class="keyword">new</span> Map([ [<span class="string">"name"</span>, <span class="string">"张三"</span>], [<span class="string">"title"</span>, <span class="string">"Author"</span>]]);</span><br><span class="line"></span><br><span class="line"><span class="built_in">map</span>.<span class="built_in">size</span> <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">map</span>.has(<span class="string">"name"</span>) <span class="comment">// true</span></span><br><span class="line"><span class="built_in">map</span>.<span class="built_in">get</span>(<span class="string">"name"</span>) <span class="comment">// "张三"</span></span><br><span class="line"><span class="built_in">map</span>.has(<span class="string">"title"</span>) <span class="comment">// true</span></span><br><span class="line"><span class="built_in">map</span>.<span class="built_in">get</span>(<span class="string">"title"</span>) <span class="comment">// "Author"</span></span><br></pre></td></tr></table></figure>
<p>如果对同一个键多次赋值，后面的值将覆盖前面的值。</p>
<p>如果读取一个未知的键，则返回undefined。</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">new <span class="function"><span class="title">Map</span><span class="params">()</span></span>.<span class="function"><span class="title">get</span><span class="params">(<span class="string">'asfddfsasadf'</span>)</span></span> <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
<p>注意，只有对同一个对象的引用，Map结构才将其视为同一个键。这一点要非常小心。</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var <span class="built_in">map</span> = <span class="keyword">new</span> Map();</span><br><span class="line"></span><br><span class="line"><span class="built_in">map</span>.<span class="built_in">set</span>([<span class="string">'a'</span>], <span class="number">555</span>);</span><br><span class="line"><span class="built_in">map</span>.<span class="built_in">get</span>([<span class="string">'a'</span>]) <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
<p>同理，同样的值的两个实例，在Map结构中被视为两个键。<br><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="built_in">map</span> = <span class="keyword">new</span> <span class="type">Map</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> k1 = ['a'];</span><br><span class="line"><span class="keyword">var</span> k2 = ['a'];</span><br><span class="line"></span><br><span class="line"><span class="built_in">map</span>.<span class="keyword">set</span>(k1, <span class="number">111</span>);</span><br><span class="line"><span class="built_in">map</span>.<span class="keyword">set</span>(k2, <span class="number">222</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">map</span>.<span class="keyword">get</span>(k1) <span class="comment">// 111</span></span><br><span class="line"><span class="built_in">map</span>.<span class="keyword">get</span>(k2) <span class="comment">// 222</span></span><br></pre></td></tr></table></figure></p>
<p>由上可知，Map的键实际上是跟内存地址绑定的，只要内存地址不一样，就视为两个键。这就解决了同名属性碰撞（clash）的问题，</p>
<p>如果Map的键是一个简单类型的值（数字、字符串、布尔值），则只要两个值严格相等，Map将其视为一个键，包括0和-0。另外，虽然NaN不严格相等于自身，但Map将其视为同一个键。</p>
<h4 id="实例的属性和操作方法">实例的属性和操作方法</h4><p>Map结构的实例有以下属性和操作方法。</p>
<ul>
<li>size：返回成员总数。</li>
<li>set(key, value)：设置key所对应的键值，然后返回整个Map结构。如果key已经有值，则键值会被更新，否则就新生成该键。</li>
<li>get(key)：读取key对应的键值，如果找不到key，返回undefined。</li>
<li>has(key)：返回一个布尔值，表示某个键是否在Map数据结构中。</li>
<li>delete(key)：删除某个键，返回true。如果删除失败，返回false。</li>
<li>clear()：清除所有成员，没有返回值。</li>
</ul>
<p>set()方法返回的是Map本身，因此可以采用链式写法。</p>
<h4 id="遍历方法">遍历方法</h4><p>Map原生提供三个Iterable对象，这三个对象同样实现了Iterator接口。</p>
<ul>
<li>keys()：返回键名的Iterable对象。</li>
<li>values()：返回键值的Iterable对象。</li>
<li>entries()：返回所有成员的Iterable对象。</li>
</ul>
<p>下面是使用实例。</p>
<figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> [key, <span class="keyword">value</span>] <span class="keyword">of</span> map.entries()) &#123;</span><br><span class="line">  console.log(key, <span class="keyword">value</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 等同于使用map.entries()</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> [key, <span class="keyword">value</span>] <span class="keyword">of</span> map) &#123;</span><br><span class="line">  console.log(key, <span class="keyword">value</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码最后的那个例子，表示Map结构的Symbol.iterator属性，就是entries方法。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">map[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] === map.entries // <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>Map结构转为数组结构，比较快速的方法是结合使用扩展运算符（…）。</p>
<figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="atom">let</span> <span class="atom">map</span> = <span class="atom">new</span> <span class="name">Map</span>([</span><br><span class="line">  [<span class="number">1</span>, <span class="string">'one'</span>],</span><br><span class="line">  [<span class="number">2</span>, <span class="string">'two'</span>],</span><br><span class="line">  [<span class="number">3</span>, <span class="string">'three'</span>],</span><br><span class="line">]);</span><br><span class="line"></span><br><span class="line">[...<span class="atom">map</span>.<span class="atom">keys</span>()]</span><br><span class="line">// [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">[...<span class="atom">map</span>.<span class="atom">values</span>()]</span><br><span class="line">// [<span class="string">'one'</span>, <span class="string">'two'</span>, <span class="string">'three'</span>]</span><br><span class="line">[...<span class="atom">map</span>.<span class="atom">entries</span>()]</span><br><span class="line">// [[<span class="number">1</span>,<span class="string">'one'</span>], [<span class="number">2</span>, <span class="string">'two'</span>], [<span class="number">3</span>, <span class="string">'three'</span>]]</span><br><span class="line">[...<span class="atom">map</span>]</span><br><span class="line">// [[<span class="number">1</span>,<span class="string">'one'</span>], [<span class="number">2</span>, <span class="string">'two'</span>], [<span class="number">3</span>, <span class="string">'three'</span>]]</span><br></pre></td></tr></table></figure>
<p>结合数组的map方法、filter方法，可以实现Map的遍历和过滤（Map本身没有map和filter方法）。</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="reserved">let</span> map0 = <span class="keyword">new</span> Map()</span><br><span class="line">  .set(<span class="number">1</span>, <span class="string">'a'</span>)</span><br><span class="line">  .set(<span class="number">2</span>, <span class="string">'b'</span>)</span><br><span class="line">  .set(<span class="number">3</span>, <span class="string">'c'</span>);</span><br><span class="line"></span><br><span class="line"><span class="reserved">let</span> map1 = <span class="keyword">new</span> Map(</span><br><span class="line">  [...map0].filter(<span class="function"><span class="params">([k, v])</span> =&gt;</span> k &lt; <span class="number">3</span>)</span><br><span class="line">);</span><br><span class="line"><span class="regexp">//</span> 产生Map结构 &#123;<span class="number">1</span> =&gt; <span class="string">'a'</span>, <span class="number">2</span> =&gt; <span class="string">'b'</span>&#125;</span><br><span class="line"><span class="reserved">let</span> map2 = <span class="keyword">new</span> Map(</span><br><span class="line">  [...map0].map(<span class="function"><span class="params">([k, v])</span> =&gt;</span> [k * <span class="number">2</span>, <span class="string">'_'</span> + v])</span><br><span class="line">    );</span><br><span class="line"><span class="regexp">//</span> 产生Map结构 &#123;<span class="number">2</span> =&gt; <span class="string">'_a'</span>, <span class="number">4</span> =&gt; <span class="string">'_b'</span>, <span class="number">6</span> =&gt; <span class="string">'_c'</span>&#125;</span><br></pre></td></tr></table></figure>
<p>此外，Map还有一个forEach方法，与数组的forEach方法类似，也可以实现遍历。</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">map</span>.forEach(function(value, key, <span class="keyword">map</span>)) &#123;</span><br><span class="line">  console.<span class="keyword">log</span>(<span class="string">"Key: <span class="variable">%s</span>, Value: <span class="variable">%s</span>"</span>, key, value);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>forEach方法还可以接受第二个参数，用来绑定this。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reporter = &#123;</span><br><span class="line">  report: <span class="function"><span class="keyword">function</span>(<span class="params">key, value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Key: %s, Value: %s"</span>, key, value);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line">map.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">value, key, map</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.report(key, value);</span><br><span class="line">&#125;, reporter);</span><br></pre></td></tr></table></figure></p>
<p>上面代码中，forEach方法的回调函数的this，就指向reporter。</p>
<h4 id="与其他数据结构的互相转换">与其他数据结构的互相转换</h4><ol>
<li><p><strong>Map转为数组</strong></p>
<p> 前面已经提过，Map转为数组最方便的方法，就是使用扩展运算符（…）。</p>
</li>
<li><p><strong>数组转为Map</strong></p>
<p> 将数组转入Map构造函数，就可以转为Map。</p>
</li>
<li><p><strong>Map转为对象</strong></p>
<p> 如果所有Map的键都是字符串，通过遍历，它可以转为对象。</p>
</li>
<li><p><strong>对象转为Map</strong></p>
<p>通过遍历Object.keys(obj)，调用map.set方法添加键值对</p>
</li>
<li><p><strong>Map转为JSON</strong></p>
<p> Map转为JSON要区分两种情况。一种情况是，Map的键名都是字符串，这时可以选择转为对象JSON。JSON.stringify(strMapToObj(strMap));</p>
<p> 另一种情况是，Map的键名有非字符串，这时可以选择转为数组JSON。 JSON.stringify([…map]);</p>
</li>
<li><p><strong>JSON转为Map</strong></p>
<p> JSON转为Map，正常情况下，所有键名都是字符串。JSON.parse(jsonStr)先转为对象，再把对象转为Map</p>
<p> 但是，有一种特殊情况，整个JSON就是一个数组，且每个数组成员本身，又是一个有两个成员的数组。这时，它可以一一对应地转为Map。这往往是数组转为JSON的逆操作。new Map(JSON.parse(jsonStr));</p>
</li>
</ol>
<h3 id="WeakMap_类型">WeakMap 类型</h3><p>WeakMap结构与Map结构基本类似，唯一的区别是它只接受对象作为键名（null除外），不接受原始类型的值作为键名，而且键名所指向的对象，不计入垃圾回收机制。</p>
<p>WeakMap的设计目的在于，键名是对象的弱引用（垃圾回收机制不将该引用考虑在内），所以其所对应的对象可能会被自动回收。当对象被回收后，WeakMap自动移除对应的键值对。典型应用是，一个对应DOM元素的WeakMap结构，当某个DOM元素被清除，其所对应的WeakMap记录就会自动被移除。基本上，WeakMap的专用场合就是，它的键所对应的对象，可能会在将来消失。WeakMap结构有助于防止内存泄漏。</p>
<p>下面是WeakMap结构的一个例子，可以看到用法上与Map几乎一样。<br><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> wm = <span class="keyword">new</span> WeakMap();</span><br><span class="line"><span class="keyword">var</span> element = <span class="built_in">document</span>.<span class="built_in">querySelector</span>(<span class="string">".element"</span>);</span><br><span class="line"></span><br><span class="line">wm.<span class="literal">set</span>(element, <span class="string">"Original"</span>);</span><br><span class="line">wm.<span class="literal">get</span>(element) <span class="comment">// "Original"</span></span><br><span class="line"></span><br><span class="line">element.parentNode.removeChild(element);</span><br><span class="line">element = <span class="keyword">null</span>;</span><br><span class="line">wm.<span class="literal">get</span>(element) <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码中，变量wm是一个WeakMap实例，我们将一个DOM节点element作为键名，然后销毁这个节点，element对应的键就自动消失了，再引用这个键名就返回undefined。</p>
<p>WeakMap与Map在API上的区别主要是两个，一是没有遍历操作（即没有key()、values()和entries()方法），也没有size属性；二是无法清空，即不支持clear方法。这与WeakMap的键不被计入引用、被垃圾回收机制忽略有关。因此，WeakMap只有四个方法可用：get()、set()、has()、delete()。</p>
<p>WeakMap的另一个用处是部署私有属性。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> _counter = <span class="keyword">new</span> WeakMap();</span><br><span class="line"><span class="keyword">let</span> _action = <span class="keyword">new</span> WeakMap();</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> Countdown &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(counter, action) </span>&#123;</span><br><span class="line">    _counter.set(<span class="keyword">this</span>, counter);</span><br><span class="line">    _action.set(<span class="keyword">this</span>, action);</span><br><span class="line">  &#125;</span><br><span class="line">  dec() &#123;</span><br><span class="line">    <span class="keyword">let</span> counter = _counter.get(<span class="keyword">this</span>);</span><br><span class="line">    <span class="keyword">if</span> (counter &lt; <span class="number">1</span>) <span class="keyword">return</span>;</span><br><span class="line">    counter--;</span><br><span class="line">    _counter.set(<span class="keyword">this</span>, counter);</span><br><span class="line">    <span class="keyword">if</span> (counter === <span class="number">0</span>) &#123;</span><br><span class="line">      _action.get(<span class="keyword">this</span>)();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> c = <span class="keyword">new</span> Countdown(<span class="number">2</span>, () =&gt; <span class="built_in">console</span>.log(<span class="string">'DONE'</span>));</span><br><span class="line"></span><br><span class="line">c.dec()</span><br><span class="line">c.dec()</span><br><span class="line"><span class="comment">// DONE</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Countdown类的两个内部属性<code>_counter</code>和<code>_action</code>，是实例的弱引用，所以如果删除实例，它们也就随之消失，不会造成内存泄漏。</p>
<h3 id="Set_类型">Set 类型</h3><h4 id="基本用法-1">基本用法</h4><p>ES6提供了新的数据结构Set。它类似于数组，但是成员的值都是唯一的，没有重复的值。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> s = <span class="keyword">new</span> <span class="built_in">Set</span>();</span><br><span class="line">[<span class="number">2</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">2</span>,<span class="number">2</span>].map(x =&gt; s.add(x))</span><br><span class="line">s<span class="comment">// Set [ 2, 3, 5, 4 ]</span></span><br></pre></td></tr></table></figure>
<p>Set函数可以接受一个数组作为参数，用来初始化。<br><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> items = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">5</span>,<span class="number">5</span>,<span class="number">5</span>]);</span><br><span class="line">items.size <span class="comment">// 5</span></span><br></pre></td></tr></table></figure></p>
<p>向Set加入值的时候，不会发生类型转换，所以5和“5”是两个不同的值。Set内部判断两个值是否不同，使用的算法类似于精确相等运算符（===），这意味着，两个对象总是不相等的。唯一的例外是NaN等于自身（精确相等运算符认为NaN不等于自身）。</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">let <span class="built_in">set</span> = <span class="keyword">new</span> Set();</span><br><span class="line"><span class="built_in">set</span>.<span class="built_in">add</span>(&#123;&#125;)</span><br><span class="line"><span class="built_in">set</span>.<span class="built_in">size</span> <span class="comment">// 1</span></span><br><span class="line"><span class="built_in">set</span>.<span class="built_in">add</span>(&#123;&#125;)</span><br><span class="line"><span class="built_in">set</span>.<span class="built_in">size</span> <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<p>上面代码表示，由于两个空对象不是精确相等，所以它们被视为两个值。</p>
<h4 id="Set实例的属性和方法">Set实例的属性和方法</h4><p>Set结构的实例有以下属性。</p>
<ul>
<li>Set.prototype.constructor：构造函数，默认就是Set函数。</li>
<li>Set.prototype.size：返回Set实例的成员总数。</li>
</ul>
<p>Set实例的方法分为两大类：操作方法（用于操作数据）和遍历方法（用于遍历成员）。下面先介绍四个操作方法。</p>
<ul>
<li>add(value)：添加某个值，返回Set结构本身。</li>
<li>delete(value)：删除某个值，返回一个布尔值，表示删除是否成功。</li>
<li>has(value)：返回一个布尔值，表示该值是否为Set的成员。</li>
<li>clear()：清除所有成员，没有返回值。</li>
</ul>
<p>Array.from方法可以将Set结构转为数组。</p>
<figure class="highlight smali"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var items =<span class="instruction"> new </span>Set(<span class="keyword">[</span>1, 2, 3, 4, 5]<span class="function">)</span>;</span><br><span class="line">var<span class="instruction"> array </span>=<span class="function"> Array.from(</span>items<span class="function">)</span>;</span><br></pre></td></tr></table></figure>
<p>这就提供了一种去除数组的重复元素的方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dedupe</span>(<span class="params">array</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Array</span>.from(<span class="keyword">new</span> <span class="built_in">Set</span>(array));</span><br><span class="line">&#125;</span><br><span class="line">dedupe([<span class="number">1</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]) <span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>
<p><strong>遍历操作</strong></p>
<p>Set结构的实例有四个遍历方法，可以用于遍历成员。</p>
<ul>
<li>keys()：返回一个键名的Iterable对象</li>
<li>values()：返回一个键值的Iterable对象</li>
<li>entries()：返回一个键值对的Iterable对象</li>
<li>forEach()：使用回调函数遍历每个成员</li>
</ul>
<p>key方法、value方法、entries方法返回的都是Iterable对象，该对象同样实现了Iterator接口。由于Set结构没有键名，只有键值（或者说键名和键值是同一个值），所以key方法和value方法的行为完全一致。</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="reserved">let</span> set = <span class="keyword">new</span> Set([<span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span>]);</span><br><span class="line"><span class="keyword">for</span> ( <span class="reserved">let</span> item <span class="keyword">of</span> set.entries() )&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(item);</span><br><span class="line">&#125;</span><br><span class="line"><span class="regexp">//</span> [<span class="string">"red"</span>, <span class="string">"red"</span>]</span><br><span class="line"><span class="regexp">//</span> [<span class="string">"green"</span>, <span class="string">"green"</span>]</span><br><span class="line"><span class="regexp">//</span> [<span class="string">"blue"</span>, <span class="string">"blue"</span>]</span><br></pre></td></tr></table></figure>
<p>Set结构的实例默认可遍历，它的默认Symbol.iterator方法就是它的values方法。<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Set</span>.prototype[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] === <span class="type">Set</span>.prototype.values</span><br><span class="line">// <span class="literal">true</span></span><br></pre></td></tr></table></figure></p>
<p>这意味着，可以省略values方法，直接用for…of循环遍历Set。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span>]);</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> x <span class="keyword">of</span> set) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(x);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>由于扩展运算符（…）内部使用for…of循环，所以也可以用于Set结构。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="built_in">set</span> <span class="subst">=</span> <span class="literal">new</span> <span class="built_in">Set</span>(<span class="preprocessor">[</span><span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span><span class="preprocessor">]</span><span class="markup">);</span><br><span class="line">let arr = </span><span class="preprocessor">[</span><span class="attribute">...</span><span class="built_in">set</span><span class="preprocessor">]</span><span class="markup">;</span><br><span class="line">// </span><span class="preprocessor">[</span><span class="string">'red'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span><span class="preprocessor">]</span><span class="markup"></span></span><br></pre></td></tr></table></figure>
<p>这就提供了另一种便捷的去除数组重复元素的方法。<br><figure class="highlight ceylon"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">3</span>, <span class="number">5</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">5</span>, <span class="number">5</span>];</span><br><span class="line"><span class="keyword">let</span> unique = [...<span class="keyword">new</span> Set(arr)];</span><br><span class="line"><span class="comment">// [3, 5, 2]</span></span><br></pre></td></tr></table></figure></p>
<p>而且，通过扩展运算符，数组的map和filter方法也可以用于Set了。<br><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">let <span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]);</span><br><span class="line"><span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([...<span class="literal">set</span>].map(x =&gt; x * <span class="number">2</span>));</span><br><span class="line"><span class="comment">// 返回Set结构：&#123;2, 4, 6&#125;</span></span><br><span class="line">let <span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]);</span><br><span class="line"><span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([...<span class="literal">set</span>].filter(x =&gt; (x % <span class="number">2</span>) == <span class="number">0</span>));</span><br><span class="line"><span class="comment">// 返回Set结构：&#123;2, 4&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>因此使用Set，可以很容易地实现并集（Union）和交集（Intersect）。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]);</span><br><span class="line"><span class="keyword">let</span> b = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>]);</span><br><span class="line"><span class="keyword">let</span> union = <span class="keyword">new</span> <span class="built_in">Set</span>([...a, ...b]);</span><br><span class="line"><span class="comment">// [1, 2, 3, 4]</span></span><br><span class="line"><span class="keyword">let</span> intersect = <span class="keyword">new</span> <span class="built_in">Set</span>([...a].filter(x =&gt; b.has(x)));</span><br><span class="line"><span class="comment">// [2, 3]</span></span><br></pre></td></tr></table></figure></p>
<p>Set结构的实例的forEach方法，用于对每个成员执行某种操作，没有返回值。<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = <span class="keyword">new</span> Set([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]);</span><br><span class="line"><span class="keyword">set</span>.forEach((<span class="keyword">value</span>, key) =&gt; console.log(<span class="keyword">value</span> * <span class="number">2</span>) )</span><br><span class="line"><span class="comment">// 2</span></span><br><span class="line"><span class="comment">// 4</span></span><br><span class="line"><span class="comment">// 6</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码说明，forEach方法的参数就是一个处理函数。该函数的参数依次为键值、键名、集合本身（上例省略了该参数）。另外，forEach方法还可以有第二个参数，表示绑定的this对象。</p>
<p>如果想在遍历操作中，同步改变原来的Set结构，目前没有直接的方法，但有两种变通方法。一种是利用原Set结构映射出一个新的结构，然后赋值给原来的Set结构；另一种是利用Array.from方法。<br><figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line">let <span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]);</span><br><span class="line"><span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([...<span class="literal">set</span>].map(val =&gt; val * <span class="number">2</span>));</span><br><span class="line"><span class="comment">// set的值是2, 4, 6</span></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line">let <span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]);</span><br><span class="line"><span class="literal">set</span> = <span class="keyword">new</span> <span class="built_in">Set</span>(Array.from(<span class="literal">set</span>, val =&gt; val * <span class="number">2</span>));</span><br><span class="line"><span class="comment">// set的值是2, 4, 6</span></span><br></pre></td></tr></table></figure></p>
<p>上面代码提供了两种方法，直接在遍历操作中改变原来的Set结构。</p>
<h3 id="WeakSet_类型">WeakSet 类型</h3><p>WeakSet结构与Set类似，也是不重复的值的集合。但是，它与Set有两个区别。</p>
<p>首先，WeakSet的成员只能是对象，而不能是其他类型的值。</p>
<p>其次，WeakSet中的对象都是弱引用，即垃圾回收机制不考虑WeakSet对该对象的引用，也就是说，如果其他对象都不再引用该对象，那么垃圾回收机制会自动回收该对象所占用的内存，不考虑该对象还存在于WeakSet之中。这个特点意味着，无法引用WeakSet的成员，因此WeakSet是不可遍历的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ws = <span class="keyword">new</span> <span class="built_in">WeakSet</span>();</span><br><span class="line">ws.add(<span class="number">1</span>)</span><br><span class="line"><span class="comment">// TypeError: Invalid value used in weak set</span></span><br></pre></td></tr></table></figure>
<p>作为构造函数，WeakSet可以接受一个数组或类似数组的对象作为参数。（实际上，任何具有iterable接口的对象，都可以作为WeakSet的对象。）该数组的所有成员，都会自动成为WeakSet实例对象的成员。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var a = <span class="string">[[1,2], [3,4]]</span>;</span><br><span class="line">var ws = new WeakSet(a);</span><br></pre></td></tr></table></figure>
<p>上面代码中，a是一个数组，它有两个成员，也都是数组。将a作为WeakSet构造函数的参数，a的成员会自动成为WeakSet的成员。</p>
<p>WeakSet结构有以下三个方法。</p>
<ul>
<li><strong>WeakSet.prototype.add(value)</strong>：向WeakSet实例添加一个新成员。</li>
<li><strong>WeakSet.prototype.delete(value)</strong>：清除WeakSet实例的指定成员。</li>
<li><strong>WeakSet.prototype.has(value)</strong>：返回一个布尔值，表示某个值是否在WeakSet实例之中。</li>
</ul>
<p>WeakSet没有size属性，没有办法遍历它的成员。</p>
<p>WeakSet不能遍历，是因为成员都是弱引用，随时可能消失，遍历机制无法保存成员的存在，很可能刚刚遍历结束，成员就取不到了。WeakSet的一个用处，是储存DOM节点，而不用担心这些节点从文档移除时，会引发内存泄漏。</p>
<h2 id="反射类型">反射类型</h2><h3 id="Proxy">Proxy</h3><p>Proxy用于修改某些操作的默认行为，等同于在语言层面做出修改，所以属于一种“元编程”（meta programming），即对编程语言进行编程。</p>
<p>Proxy可以理解成，在目标对象之前架设一层“拦截”，外界对该对象的访问，都必须先通过这层拦截，因此提供了一种机制，可以对外界的访问进行过滤和改写。Proxy这个词的原意是代理，用在这里表示由它来“代理”某些操作，可以译为“代理器”。（与Java中动态代理类似）</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">var</span> proxy = new <span class="function"><span class="title">Proxy</span><span class="params">(target, handler)</span></span></span><br></pre></td></tr></table></figure>
<p>Proxy对象的所有用法，都是上面这种形式，不同的只是handler参数的写法。其中，<code>new Proxy()</code>表示生成一个Proxy实例，target参数表示所要拦截的目标对象，handler参数也是一个对象，用来定制拦截行为。</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> proxy = <span class="keyword">new</span> Proxy(&#123;&#125;, &#123;</span><br><span class="line">  <span class="keyword">get</span>: <span class="function"><span class="keyword">function</span><span class="params">(target, property)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">35</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">proxy.time <span class="comment">// 35</span></span><br><span class="line">proxy.name <span class="comment">// 35</span></span><br><span class="line">proxy.title <span class="comment">// 35</span></span><br></pre></td></tr></table></figure>
<p>注意，要使得Proxy起作用，必须针对Proxy实例（上例是proxy对象）进行操作，而不是针对目标对象（上例是空对象）进行操作。</p>
<p>一个技巧是将Proxy对象，设置到<code>object.proxy</code>属性，从而可以在object对象上调用。</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var object = &#123; proxy: <span class="keyword">new</span> Proxy(<span class="keyword">target</span>, <span class="keyword">handler</span>) &#125;</span><br></pre></td></tr></table></figure>
<p>Proxy实例也可以作为其他对象的原型对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> proxy = <span class="keyword">new</span> <span class="built_in">Proxy</span>(&#123;&#125;, &#123;</span><br><span class="line">  get: <span class="function"><span class="keyword">function</span>(<span class="params">target, property</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">35</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj = <span class="built_in">Object</span>.create(proxy);</span><br><span class="line">obj.time <span class="comment">// 35</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，proxy对象是obj对象的原型，obj对象本身并没有time属性，所有根据原型链，会在proxy对象上读取该属性，导致被拦截。</p>
<p>下面是Proxy支持的拦截操作一览。</p>
<p>对于可以设置、但没有设置拦截的操作，则直接落在目标对象上，按照原先的方式产生结果。</p>
<ol>
<li><p><strong>get(target, propKey, receiver)</strong></p>
<p> 拦截对象属性的读取，比如<code>proxy.foo</code>和<code>proxy[&#39;foo&#39;]</code>，返回类型不限。最后一个参数receiver可选，当target对象设置了propKey属性的get函数时，receiver对象会绑定get函数的this对象。</p>
</li>
<li><p><strong>set(target, propKey, value, receiver)</strong></p>
<p> 拦截对象属性的设置，比如<code>proxy.foo = v</code>或<code>proxy[&#39;foo&#39;] = v</code>，返回一个布尔值。</p>
</li>
<li><p><strong>has(target, propKey)</strong></p>
<p> 拦截<code>propKey in proxy</code>的操作，返回一个布尔值。</p>
</li>
<li><p><strong>deleteProperty(target, propKey)</strong></p>
<p> 拦截<code>delete proxy[propKey]</code>的操作，返回一个布尔值。</p>
</li>
<li><p><strong>enumerate(target)</strong></p>
<p> 拦截<code>for (var x in proxy)</code>，返回一个Iterable对象。</p>
</li>
<li><p><strong>hasOwn(target, propKey)</strong></p>
<p> 拦截<code>proxy.hasOwnProperty(&#39;foo&#39;)</code>，返回一个布尔值。</p>
</li>
<li><p><strong>ownKeys(target)</strong></p>
<p> 拦截<code>Object.getOwnPropertyNames(proxy)</code>、<code>Object.getOwnPropertySymbols(proxy)</code>、<code>Object.keys(proxy)</code>，返回一个数组。该方法返回对象所有自身的属性，而<code>Object.keys()</code>仅返回对象可遍历的属性。</p>
</li>
<li><p><strong>getOwnPropertyDescriptor(target, propKey)</strong></p>
<p> 拦截<code>Object.getOwnPropertyDescriptor(proxy, propKey)</code>，返回属性的描述对象。</p>
</li>
<li><p><strong>defineProperty(target, propKey, propDesc)</strong></p>
<p> 拦截<code>Object.defineProperty(proxy, propKey, propDesc）</code>、<code>Object.defineProperties(proxy, propDescs)</code>，返回一个布尔值。</p>
</li>
<li><p><strong>preventExtensions(target)</strong></p>
<p>拦截<code>Object.preventExtensions(proxy)</code>，返回一个布尔值。</p>
</li>
<li><p><strong>getPrototypeOf(target)</strong></p>
<p>拦截<code>Object.getPrototypeOf(proxy)</code>，返回一个对象。</p>
</li>
<li><p><strong>isExtensible(target)</strong></p>
<p>拦截<code>Object.isExtensible(proxy)</code>，返回一个布尔值。</p>
</li>
<li><p><strong>setPrototypeOf(target, proto)</strong></p>
<p>拦截<code>Object.setPrototypeOf(proxy, proto)</code>，返回一个布尔值。</p>
</li>
</ol>
<p>如果目标对象是函数，那么还有两种额外操作可以拦截。</p>
<ol>
<li><p><strong>apply(target, object, args)</strong></p>
<p> 拦截Proxy实例作为函数调用的操作，比如<code>proxy(...args)</code>、<code>proxy.call(object, ...args)</code>、<code>proxy.apply(...)</code>。</p>
</li>
<li><p><strong>construct(target, args, proxy)</strong></p>
<p> 拦截Proxy实例作为构造函数调用的操作，比如new proxy(…args)。</p>
</li>
</ol>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//get</span></span><br><span class="line"><span class="keyword">var</span> person = &#123;</span><br><span class="line">  name: <span class="string">"张三"</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> proxy = <span class="keyword">new</span> Proxy(person, &#123;</span><br><span class="line">  <span class="keyword">get</span>: <span class="function"><span class="keyword">function</span><span class="params">(target, property)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (property <span class="keyword">in</span> target) &#123;</span><br><span class="line">      <span class="keyword">return</span> target[property];</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> ReferenceError(<span class="string">"Property \""</span> + property + <span class="string">"\" does not exist."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">proxy.name <span class="comment">// "张三"</span></span><br><span class="line">proxy.age <span class="comment">// 抛出一个错误</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//apply</span></span><br><span class="line"><span class="keyword">var</span> target = <span class="function"><span class="keyword">function</span> <span class="params">()</span> </span>&#123; <span class="keyword">return</span> <span class="string">'I am the target'</span>; &#125;;</span><br><span class="line"><span class="keyword">var</span> handler = &#123;</span><br><span class="line">  apply: <span class="function"><span class="keyword">function</span> <span class="params">(receiver, <span class="rest_arg">...args</span>)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'I am the proxy'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> p = <span class="keyword">new</span> Proxy(target, handler);</span><br><span class="line"></span><br><span class="line">p() === <span class="string">'I am the proxy'</span>; <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<h3 id="Reflect">Reflect</h3><p>Reflect对象与Proxy对象一样，也是ES6为了操作对象而提供的新API。Reflect对象的设计目的有这样几个。</p>
<ol>
<li>将Object对象的一些明显属于语言层面的方法，放到Reflect对象上。现阶段，某些方法同时在Object和Reflect对象上部署，未来的新方法将只部署在Reflect对象上。</li>
<li>修改某些Object方法的返回结果，让其变得更合理。比如，<code>Object.defineProperty(obj, name, desc)</code>在无法定义属性时，会抛出一个错误，而<code>Reflect.defineProperty(obj, name, desc)</code>则会返回false。</li>
<li>让Object操作都变成函数行为。某些Object操作是命令式，比如<code>name in obj</code>和<code>delete obj[name]</code>，而<code>Reflect.has(obj, name)</code>和<code>Reflect.deleteProperty(obj, name)</code>让它们变成了函数行为。</li>
<li>Reflect对象的方法与Proxy对象的方法一一对应，只要是Proxy对象的方法，就能在Reflect对象上找到对应的方法。这就让Proxy对象可以方便地调用对应的Reflect方法，完成默认行为，作为修改行为的基础。</li>
</ol>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Proxy(target, &#123;</span><br><span class="line">  <span class="keyword">set</span>: function(target, <span class="property">name</span>, value, receiver) &#123;</span><br><span class="line">    var success = Reflect.<span class="keyword">set</span>(target,<span class="property">name</span>, value, receiver);</span><br><span class="line">    <span class="keyword">if</span> (success) &#123;</span><br><span class="line">      <span class="command">log</span>('<span class="keyword">property</span> '+<span class="property">name</span>+' <span class="function_start"><span class="keyword">on</span></span> '+target+' <span class="keyword">set</span> <span class="keyword">to</span> '+value);</span><br><span class="line">    &#125;</span><br><span class="line"><span class="command">    return</span> success;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>Reflect对象的方法清单如下。</p>
<ul>
<li>Reflect.getOwnPropertyDescriptor(target,name)</li>
<li>Reflect.defineProperty(target,name,desc)</li>
<li>Reflect.getOwnPropertyNames(target)</li>
<li>Reflect.getPrototypeOf(target) 读取对象的<code>__proto__</code>属性，等同于<code>Object.getPrototypeOf(obj)</code>。</li>
<li>Reflect.setPrototypeOf(obj, newProto) 设置对象的<code>__proto__</code>属性，注意，Object对象没有对应这个方法的方法。</li>
<li>Reflect.deleteProperty(target,name) 等同于<code>delete obj[name]</code>。</li>
<li>Reflect.enumerate(target)</li>
<li>Reflect.freeze(target)</li>
<li>Reflect.seal(target)</li>
<li>Reflect.preventExtensions(target)</li>
<li>Reflect.isFrozen(target)</li>
<li>Reflect.isSealed(target)</li>
<li>Reflect.isExtensible(target)</li>
<li>Reflect.has(target,name) 等同于<code>name in obj</code>。</li>
<li>Reflect.hasOwn(target,name)</li>
<li>Reflect.keys(target)</li>
<li>Reflect.get(target,name,receiver) 查找并返回target对象的name属性，如果没有该属性，则返回undefined。如果name属性部署了读取函数，则读取函数的this绑定receiver。</li>
<li>Reflect.set(target,name,value,receiver) 设置target对象的name属性等于value。如果name属性设置了赋值函数，则赋值函数的this绑定receiver。</li>
<li>Reflect.apply(target,thisArg,args) 等同于<code>Function.prototype.apply.call(fun,thisArg,args)</code>。一般来说，如果要绑定一个函数的this对象，可以这样写<code>fn.apply(obj, args)</code>，但是如果函数定义了自己的apply方法，就只能写成<code>Function.prototype.apply.call(fn, obj, args)</code>，采用Reflect对象可以简化这种操作。</li>
<li>Reflect.construct(target,args) 等同于<code>new target(...args)</code>，这提供了一种不使用new，来调用构造函数的方法。</li>
</ul>
<p>注意，Reflect.set()、Reflect.defineProperty()、Reflect.freeze()、Reflect.seal()和Reflect.preventExtensions()返回一个布尔值，表示操作是否成功。它们对应的Object方法，失败时都会抛出错误。</p>
<h2 id="控制抽象类型">控制抽象类型</h2><h3 id="Iteration_接口">Iteration 接口</h3><p>ECMAScript 中一个接口是一组键值对属性，这些属性的键所对应的值符合特定的规范。如果一个对象提供了一个接口描述的所有属性，那么这个对象就实现了这个接口。一个接口并不是被单独的一个对象表示。可能有很多单独的对象实现符合某个接口，一个单独的对象可能实现多个接口。</p>
<p>通过统一的接口机制，可以使用for-of来遍历不同的数据结构。</p>
<h4 id="Iterable_接口">Iterable 接口</h4><p>这个接口只有一个属性，即Symbol.iterator，它是一个函数，这个函数返回一个实现了Iterator接口的对象。</p>
<p>在ES6中，有些数据结构原生实现了这个接口（比如数组），不用任何处理，就可以被for…of循环遍历，有些就不行（比如对象）。原因在于，这些数据结构原生部署了Symbol.iterator属性（详见下文），另外一些数据结构没有。凡是部署了Symbol.iterator属性的数据结构，就称为实现了Iterable接口。调用这个接口，就会返回一个Iterator对象。</p>
<h4 id="Iterator_接口">Iterator 接口</h4><p>这个接口有一个属性，next，这个属性是一个函数，它返回一个实现了IteratorResult接口的对象。如果上一步调用next返回的对象的done属性已经是true了，那么之后调用next函数也要返回一个done属性为true的IteratorResult对象。这个要求并不是强制的。</p>
<p>该接口还有两个可选的属性return 和 throw。这两个属性都是方法，并且方法返回值都是IteratorResult对象。</p>
<p>done为true，即遍历结束时，如果存在return方法，value的值会被设置为return方法。这并不是强制要求的。</p>
<h4 id="IteratorResult_接口">IteratorResult 接口</h4><p>包含value和done两个属性的对象。其中，value属性是当前成员的值，如果iterator提供了return方法的花，done为true时，这个value应该是iterator的return属性的值即return函数，否则done为true时value就是undefined，这种情况下可以没有value属性；done属性是一个布尔值，表示遍历是否结束，如果不存在done，就认为done属性为false。</p>
<h4 id="实例">实例</h4><p>如果使用TypeScript的写法，可以描述如下。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="type">Iterable</span> &#123;</span><br><span class="line">  [<span class="type">Symbol</span>.<span class="keyword">iterator</span>]() : <span class="type">Iterator</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="type">Iterator</span> &#123;</span><br><span class="line">  next(value?: <span class="type">any</span>) : <span class="type">IterationResult</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="type">IterationResult</span> &#123;</span><br><span class="line">  value: <span class="type">any</span>,</span><br><span class="line">  done: boolean,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面看一个例子<br><figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">function <span class="type">Obj</span>(value)&#123;</span><br><span class="line">  this.value = value;</span><br><span class="line">  this.next = null;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">Obj</span>.prototype[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] = function()&#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> <span class="keyword">iterator</span> = &#123;</span><br><span class="line">    next: next,</span><br><span class="line">    <span class="keyword">return</span>: returnFn</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> current = this;</span><br><span class="line"></span><br><span class="line">  function next()&#123;</span><br><span class="line">    <span class="keyword">if</span> (current)&#123;</span><br><span class="line">      <span class="keyword">var</span> value = current.value;</span><br><span class="line">      <span class="keyword">var</span> done = current === null;</span><br><span class="line">      current = current.next;</span><br><span class="line">      <span class="keyword">return</span> &#123;</span><br><span class="line">        done: done,</span><br><span class="line">        value: value</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> &#123;</span><br><span class="line">        value: <span class="keyword">iterator</span>.<span class="keyword">return</span>,</span><br><span class="line">        done: <span class="literal">true</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  function returnFn()&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      done: <span class="literal">true</span>,</span><br><span class="line">      value: '<span class="keyword">return</span>'</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">iterator</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> one = new <span class="type">Obj</span>(<span class="number">1</span>);</span><br><span class="line"><span class="keyword">var</span> two = new <span class="type">Obj</span>(<span class="number">2</span>);</span><br><span class="line"><span class="keyword">var</span> three = new <span class="type">Obj</span>(<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line">one.next = two;</span><br><span class="line">two.next = three;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> it = one[<span class="type">Symbol</span>.<span class="keyword">iterator</span>]();</span><br><span class="line">it.next();</span><br><span class="line">it.next();</span><br><span class="line">it.next();</span><br><span class="line">it.next().value();</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> a <span class="keyword">of</span> one)&#123;</span><br><span class="line">  console.log(a);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面代码首先在构造函数的原型链上部署Symbol.iterator方法，调用该方法会返回遍Iterator对象，调用该对象的next方法，在返回一个值的同时，自动将内部指针移到下一个实例。</p>
<h4 id="默认实现Iterable接口的数据结构">默认实现Iterable接口的数据结构</h4><p>Iterable接口的目的，就是为所有数据结构，提供了一种统一的访问机制，即for…of循环（详见下文）。当使用for…of循环遍历某种数据结构时，该循环会自动去寻找Iterable接口。</p>
<p>ES6规定，默认的Iterator接口部署在数据结构的<code>Symbol.iterator</code>属性，或者一个数据结构只要具有<code>Symbol.iterator</code>属性，就可以认为是“可遍历的”（iterable）。也就是说，调用<code>Symbol.iterator</code>方法，就会得到当前数据结构的默认Iterator对象。<code>Symbol.iterator</code>本身是一个表达式，返回Symbol对象的iterator属性，这是一个预定义好的、类型为Symbol的特殊值，所以要放在方括号内。</p>
<p>在ES6中，有三类数据结构原生具备Iterable接口：数组、某些类似数组的对象、Set和Map结构。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">let</span> arr = [<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>];</span><br><span class="line"><span class="built_in">let</span> iter = arr[Symbol.iterator]();</span><br><span class="line"></span><br><span class="line">iter.next() // &#123; value: <span class="string">'a'</span>, <span class="keyword">done</span>: <span class="literal">false</span> &#125;</span><br><span class="line">iter.next() // &#123; value: <span class="string">'b'</span>, <span class="keyword">done</span>: <span class="literal">false</span> &#125;</span><br><span class="line">iter.next() // &#123; value: <span class="string">'c'</span>, <span class="keyword">done</span>: <span class="literal">false</span> &#125;</span><br><span class="line">iter.next() // &#123; value: undefined, <span class="keyword">done</span>: <span class="literal">true</span> &#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，变量arr是一个数组，原生就具有Iterable接口，部署在arr的Symbol.iterator属性上面。所以，调用这个属性，就得到Iterator对象。</p>
<p>上面提到，原生就部署Iterable接口的数据结构有三类，对于这三类数据结构，for…of循环会自动遍历它们。除此之外，其他数据结构（主要是对象）的Iterable接口，都需要自己在Symbol.iterator属性上面部署，这样才会被for…of循环遍历。</p>
<p>对象（Object）之所以没有默认部署Iterable接口，是因为对象的哪个属性先遍历，哪个属性后遍历是不确定的，需要开发者手动指定。本质上，遍历是一种线性处理，对于任何非线性的数据结构，部署Iterable接口，就等于部署一种线性转换。不过，严格地说，对象部署Iterable接口并不是很必要，因为这时对象实际上被当作Map结构使用，ES5没有Map结构，而ES6原生提供了。</p>
<p>一个对象如果要有可被for…of循环调用的Iterable接口，就必须有Symbol.iterator方法（原型链上的对象具有该方法也可）。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> RangeIterator &#123;</span><br><span class="line">  <span class="constructor"><span class="keyword">constructor</span>(start, stop) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.value = start;</span><br><span class="line">    <span class="keyword">this</span>.stop = stop;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  [Symbol.iterator]() &#123; <span class="keyword">return</span> <span class="keyword">this</span>; &#125;</span><br><span class="line"></span><br><span class="line">  next() &#123;</span><br><span class="line">    <span class="keyword">var</span> value = <span class="keyword">this</span>.value;</span><br><span class="line">    <span class="keyword">if</span> (value &lt; <span class="keyword">this</span>.stop) &#123;</span><br><span class="line">      <span class="keyword">this</span>.value++;</span><br><span class="line">      <span class="keyword">return</span> &#123;done: <span class="literal">false</span>, value: value&#125;;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> &#123;done: <span class="literal">true</span>, value: <span class="literal">undefined</span>&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">range</span>(<span class="params">start, stop</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> RangeIterator(start, stop);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> value of range(<span class="number">0</span>, <span class="number">3</span>)) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面是另一个为对象添加Iterator接口的例子。<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> obj = &#123;</span><br><span class="line">  data: [ <span class="string">'hello'</span>, <span class="string">'world'</span> ],</span><br><span class="line">  [Symbol.iterator]() &#123;</span><br><span class="line">    <span class="keyword">const</span> self = <span class="keyword">this</span>;</span><br><span class="line">    <span class="keyword">let</span> index = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      next() &#123;</span><br><span class="line">        <span class="keyword">if</span> (index &lt; self.data.length) &#123;</span><br><span class="line">          <span class="keyword">return</span> &#123;</span><br><span class="line">            <span class="keyword">value</span>: self.data[index++],</span><br><span class="line">            done: <span class="keyword">false</span></span><br><span class="line">          &#125;;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="keyword">return</span> &#123; <span class="keyword">value</span>: undefined, done: <span class="keyword">true</span> &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>对于类似数组的对象（存在数值键名和length属性），部署Iterable接口，有一个简便方法，就是<code>Symbol.iterator</code>方法直接引用数组的Iterable接口。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">NodeList</span>.prototype[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] = <span class="type">Array</span>.prototype[<span class="type">Symbol</span>.<span class="keyword">iterator</span>];</span><br><span class="line">// 或者</span><br><span class="line"><span class="type">NodeList</span>.prototype[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] = [][<span class="type">Symbol</span>.<span class="keyword">iterator</span>];</span><br><span class="line">[...document.querySelectorAll('<span class="keyword">div</span>')] // 可以执行了</span><br></pre></td></tr></table></figure>
<p>如果Symbol.iterator方法返回的不是Iterator对象，解释引擎将会报错。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">obj[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] = () =&gt; <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">[...obj] // <span class="type">TypeError</span>: [] <span class="keyword">is</span> <span class="keyword">not</span> a function</span><br></pre></td></tr></table></figure>
<p>有了Iterable接口，数据结构就可以用for…of循环遍历，也可以使用while循环遍历。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> $<span class="keyword">iterator</span> = <span class="type">ITERABLE</span>[<span class="type">Symbol</span>.<span class="keyword">iterator</span>]();</span><br><span class="line"><span class="keyword">var</span> $<span class="literal">result</span> = $<span class="keyword">iterator</span>.next();</span><br><span class="line"><span class="keyword">while</span> (!$<span class="literal">result</span>.done) &#123;</span><br><span class="line">  <span class="keyword">var</span> x = $<span class="literal">result</span>.value;</span><br><span class="line">  // ...</span><br><span class="line">  $<span class="literal">result</span> = $<span class="keyword">iterator</span>.next();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，ITERABLE代表某种可遍历的数据结构</p>
<h4 id="Iterable接口默认的应用场合">Iterable接口默认的应用场合</h4><p>有一些场合会默认使用Iterable接口（即调用Symbol.iterator方法），除了for…of循环，还有几个别的场合。</p>
<p><strong>解构赋值</strong></p>
<figure class="highlight vim"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = <span class="keyword">new</span> Set().<span class="built_in">add</span>(<span class="string">'a'</span>).<span class="built_in">add</span>(<span class="string">'b'</span>).<span class="built_in">add</span>(<span class="string">'c'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> [<span class="keyword">x</span>,<span class="keyword">y</span>] = <span class="keyword">set</span>;</span><br><span class="line">// <span class="keyword">x</span>=<span class="string">'a'</span>; <span class="keyword">y</span>=<span class="string">'b'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> [<span class="keyword">first</span>, ...rest] = <span class="keyword">set</span>; // <span class="keyword">first</span>=<span class="string">'a'</span>; rest=[<span class="string">'b'</span>,<span class="string">'c'</span>];</span><br></pre></td></tr></table></figure>
<p><strong>扩展运算符</strong></p>
<figure class="highlight prolog"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">// 例一</span><br><span class="line"><span class="atom">var</span> <span class="atom">str</span> = <span class="string">'hello'</span>;</span><br><span class="line">[...<span class="atom">str</span>] //  [<span class="string">'h'</span>,<span class="string">'e'</span>,<span class="string">'l'</span>,<span class="string">'l'</span>,<span class="string">'o'</span>]</span><br><span class="line"></span><br><span class="line">// 例二</span><br><span class="line"><span class="atom">let</span> <span class="atom">arr</span> = [<span class="string">'b'</span>, <span class="string">'c'</span>];</span><br><span class="line">[<span class="string">'a'</span>, ...<span class="atom">arr</span>, <span class="string">'d'</span>]</span><br><span class="line">// [<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>]</span><br></pre></td></tr></table></figure>
<p>实际上，这提供了一种简便机制，可以将任何实现了Iterable接口的数据结构，转为数组。也就是说，只要某个数据结构实现了Iterable接口，就可以对它使用扩展运算符，将其转为数组。</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr <span class="subst">=</span> <span class="preprocessor">[</span><span class="attribute">...</span>iterable<span class="preprocessor">]</span><span class="markup">;</span></span><br></pre></td></tr></table></figure>
<p><strong><code>yield*</code></strong></p>
<p><code>yield*</code>后面跟的是一个实现了Iterable的对象，它会调用该对象的Symbol.iterator方法。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> generator = function* () &#123;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">yield</span>* [<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]; //use an iterable, <span class="keyword">is</span> looped, <span class="keyword">and</span> added <span class="keyword">as</span> yields</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">5</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> <span class="keyword">iterator</span> = generator();</span><br><span class="line"></span><br><span class="line"><span class="keyword">iterator</span>.next() // &#123; value: <span class="number">1</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next() // &#123; value: <span class="number">2</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next() // &#123; value: <span class="number">3</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next() // &#123; value: <span class="number">4</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next() // &#123; value: <span class="number">5</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next() // &#123; value: undefined, done: <span class="literal">true</span> &#125;</span><br></pre></td></tr></table></figure>
<p><strong>其他场合</strong></p>
<p>由于数组的遍历会调用Symbol.iterator方法，所以任何接受数组作为参数的场合，其实都调用了Symbol.iterator。下面是一些例子。</p>
<ul>
<li>Array.from()</li>
<li>Map(), Set(), WeakMap(), WeakSet()（比如<code>new Map([[&#39;a&#39;,1],[&#39;b&#39;,2]])</code>）</li>
<li>Promise.all()</li>
<li>Promise.race()</li>
</ul>
<h4 id="原生具备Iterable接口的数据结构">原生具备Iterable接口的数据结构</h4><p>ES6对数组提供entries()、keys()和values()三个方法，就是返回三个Iterable对象。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">5</span>, <span class="number">7</span>];</span><br><span class="line"><span class="keyword">var</span> arrEntries = arr.entries();</span><br><span class="line"></span><br><span class="line">arrEntries.toString() // <span class="string">"[object Array Iterator]"</span></span><br><span class="line"></span><br><span class="line">arrEntries === arrEntries[<span class="type">Symbol</span>.<span class="keyword">iterator</span>]() // <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，entries方法返回的是一个Iterator对象，本质上就是调用了<code>Symbol.iterator</code>方法。</p>
<p>字符串是一个类似数组的对象，也原生具有Iterable接口。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> someString = <span class="string">"hi"</span>;</span><br><span class="line">typeof someString[<span class="type">Symbol</span>.<span class="keyword">iterator</span>]</span><br><span class="line">// <span class="string">"function"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> <span class="keyword">iterator</span> = someString[<span class="type">Symbol</span>.<span class="keyword">iterator</span>]();</span><br><span class="line"></span><br><span class="line"><span class="keyword">iterator</span>.next()  // &#123; value: <span class="string">"h"</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next()  // &#123; value: <span class="string">"i"</span>, done: <span class="literal">false</span> &#125;</span><br><span class="line"><span class="keyword">iterator</span>.next()  // &#123; value: undefined, done: <span class="literal">true</span> &#125;</span><br></pre></td></tr></table></figure>
<p>可以覆盖原生的<code>Symbol.iterator</code>方法，达到修改Iterator对象行为的目的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">"hi"</span>);</span><br><span class="line"></span><br><span class="line">[...str] <span class="comment">// ["h", "i"]</span></span><br><span class="line"></span><br><span class="line">str[<span class="built_in">Symbol</span>.iterator] = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    next: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>._first) &#123;</span><br><span class="line">        <span class="keyword">this</span>._first = <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span> &#123; value: <span class="string">"bye"</span>, done: <span class="literal">false</span> &#125;;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> &#123; done: <span class="literal">true</span> &#125;;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    _first: <span class="literal">true</span></span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">[...str] <span class="comment">// ["bye"]</span></span><br><span class="line">str <span class="comment">// "hi"</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，字符串str的<code>Symbol.iterator</code>方法被修改了，所以扩展运算符（…）返回的值变成了bye，而字符串本身还是hi。</p>
<h4 id="Iterable接口与Generator函数">Iterable接口与Generator函数</h4><p><code>Symbol.iterator</code>方法的最简单实现，还是使用后面要介绍的Generator函数。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myIterable = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">myIterable[<span class="type">Symbol</span>.<span class="keyword">iterator</span>] = function* () &#123;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">2</span>;</span><br><span class="line">  <span class="keyword">yield</span> <span class="number">3</span>;</span><br><span class="line">&#125;;</span><br><span class="line">[...myIterable] // [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"></span><br><span class="line">// 或者采用下面的简洁写法</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj = &#123;</span><br><span class="line">  * [<span class="type">Symbol</span>.<span class="keyword">iterator</span>]() &#123;</span><br><span class="line">    <span class="keyword">yield</span> 'hello';</span><br><span class="line">    <span class="keyword">yield</span> 'world';</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> x <span class="keyword">of</span> obj) &#123;</span><br><span class="line">  console.log(x);</span><br><span class="line">&#125;</span><br><span class="line">// hello</span><br><span class="line">// world</span><br></pre></td></tr></table></figure>
<p>上面代码中，<code>Symbol.iterator</code>方法几乎不用部署任何代码，只要用yield命令给出每一步的返回值即可。</p>
<h3 id="Promise_类型">Promise 类型</h3><h4 id="Promise的含义">Promise的含义</h4><p>Promise在JavaScript语言早有实现，ES6将其写进了语言标准，统一了用法，原生提供了Promise对象。</p>
<p>所谓Promise，就是一个对象，用来传递异步操作的消息。它代表了某个未来才会知道结果的事件（通常是一个异步操作），并且这个事件提供统一的API，可供进一步处理。</p>
<p>Promise对象有以下两个特点。</p>
<ol>
<li>对象的状态不受外界影响。Promise对象代表一个异步操作，有三种状态：Pending（进行中）、Resolved（已完成，又称Fulfilled）和Rejected（已失败）。只有异步操作的结果，可以决定当前是哪一种状态，任何其他操作都无法改变这个状态。这也是Promise这个名字的由来，它的英语意思就是“承诺”，表示其他手段无法改变。</li>
<li>一旦状态改变，就不会再变，任何时候都可以得到这个结果。Promise对象的状态改变，只有两种可能：从Pending变为Resolved和从Pending变为Rejected。只要这两种情况发生，状态就凝固了，不会再变了，会一直保持这个结果。就算改变已经发生了，你再对Promise对象添加回调函数，也会立即得到这个结果。这与事件（Event）完全不同，事件的特点是，如果你错过了它，再去监听，是得不到结果的。</li>
</ol>
<p>有了Promise对象，就可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数。此外，Promise对象提供统一的接口，使得控制异步操作更加容易。</p>
<p>Promise也有一些缺点。首先，无法取消Promise，一旦新建它就会立即执行，无法中途取消。其次，如果不设置回调函数，Promise内部抛出的错误，不会反应到外部。第三，当处于Pending状态时，无法得知目前进展到哪一个阶段（刚刚开始还是即将完成）。</p>
<p>如果某些事件不断地反复发生，一般来说，使用stream模式是比部署Promise更好的选择。</p>
<h4 id="基本用法-2">基本用法</h4><p>ES6规定，Promise对象是一个构造函数，用来生成Promise实例。</p>
<p>下面代码创造了一个Promise实例。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// ... some code</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="comment">/* 异步操作成功 */</span>)&#123;</span><br><span class="line">    resolve(value);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    reject(error);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>Promise构造函数接受一个函数作为参数，该函数的两个参数分别是resolve和reject。它们是两个函数，由JavaScript引擎提供，不用自己部署。</p>
<p>resolve函数的作用是，将Promise对象的状态从“未完成”变为“成功”（即从Pending变为Resolved），在异步操作成功时调用，并将异步操作的结果，作为参数传递出去；reject函数的作用是，将Promise对象的状态从“未完成”变为“失败”（即从Pending变为Rejected），在异步操作失败时调用，并将异步操作报出的错误，作为参数传递出去。</p>
<p>Promise实例生成以后，可以用then方法分别指定Resolved状态和Reject状态的回调函数。</p>
<figure class="highlight scilab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="transposed_variable">promise.</span><span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(value)</span> &#123;</span></span><br><span class="line">  <span class="comment">// success</span></span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span><span class="params">(value)</span> &#123;</span></span><br><span class="line">  <span class="comment">// failure</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为Resolved时调用，第二个回调函数是Promise对象的状态变为Reject时调用。其中，第二个函数是可选的，不一定要提供。这两个函数都接受Promise对象传出的值作为参数。</p>
<p>下面是一个Promise对象的简单例子。</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="reserved">function</span> timeout(ms) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> Promise(<span class="function"><span class="params">(resolve)</span> =&gt;</span> &#123;</span><br><span class="line">    setTimeout(resolve, ms, <span class="string">'done'</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="reserved">var</span> to = timeout(<span class="number">8000</span>);</span><br><span class="line">to.<span class="keyword">then</span>(<span class="function"><span class="params">(value)</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(value);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="regexp">//</span>没有输出done前命令行查看to，输出后再查看，两次状态不同</span><br></pre></td></tr></table></figure>
<p>上面代码中，timeout方法返回一个Promise实例，表示一段时间以后才会发生的结果。过了指定的时间（ms参数）以后，Promise实例的状态变为Resolved，就会触发then方法绑定的回调函数。</p>
<p>下面是一个用Promise对象实现的Ajax操作的例子。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> getJSON = <span class="function"><span class="keyword">function</span>(<span class="params">url</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> client = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">    client.open(<span class="string">"GET"</span>, url);</span><br><span class="line">    client.onreadystatechange = handler;</span><br><span class="line">    client.responseType = <span class="string">"json"</span>;</span><br><span class="line">    client.setRequestHeader(<span class="string">"Accept"</span>, <span class="string">"application/json"</span>);</span><br><span class="line">    client.send();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">handler</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="keyword">this</span>.status === <span class="number">200</span>) &#123;</span><br><span class="line">        resolve(<span class="keyword">this</span>.response);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="keyword">this</span>.statusText));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> promise;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">getJSON(<span class="string">"/posts.json"</span>).then(<span class="function"><span class="keyword">function</span>(<span class="params">json</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'Contents: '</span> + json);</span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.error(<span class="string">'出错了'</span>, error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，getJSON是对XMLHttpRequest对象的封装，用于发出一个针对JSON数据的HTTP请求，并且返回一个Promise对象。需要注意的是，在getJSON内部，resolve函数和reject函数调用时，都带有参数。</p>
<p>如果调用resolve函数和reject函数时带有参数，那么它们的参数会被传递给回调函数。reject函数的参数通常是Error对象的实例，表示抛出的错误；resolve函数的参数除了正常的值以外，还可能是另一个Promise实例，表示异步操作的结果有可能是一个值，也有可能是另一个异步操作，比如像下面这样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">  <span class="comment">//可以在这里加resolve或reject方法，观察p1和p2的状态</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> p2 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">  resolve(p1);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>上面代码中，p1和p2都是Promise的实例，但是p2的resolve方法将p1作为参数，即一个异步操作的结果是返回另一个异步操作。</p>
<p>注意，这时p1的状态就会传递给p2，也就是说，p1的状态决定了p2的状态。如果p1的状态是Pending，那么p2的回调函数就会等待p1的状态改变；如果p1的状态已经是Resolved或者Rejected，那么p2的回调函数将会立刻执行。</p>
<h4 id="Promise-prototype-then()">Promise.prototype.then()</h4><p>then方法是定义在原型对象Promise.prototype上的。它的作用是为Promise实例添加状态改变时的回调函数。前面说过，then方法的第一个参数是Resolved状态的回调函数，第二个参数（可选）是Rejected状态的回调函数。</p>
<p>then方法返回的是一个新的Promise实例（注意，不是原来那个Promise实例）。因此可以采用链式写法，即then方法后面再调用另一个then方法。</p>
<figure class="highlight scilab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">"/posts.json"</span>).<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(json)</span> &#123;</span></span><br><span class="line">  <span class="keyword">return</span> <span class="transposed_variable">json.</span>post;</span><br><span class="line">&#125;).<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(post)</span> &#123;</span></span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面的代码使用then方法，依次指定了两个回调函数。第一个then方法的回调函数完成以后，会将返回结果作为参数，传入第二个then方法的回调函数。</p>
<p>采用链式的then，可以指定一组按照次序调用的回调函数。这时，前一个回调函数，有可能返回的还是一个Promise对象（即有异步操作），这时后一个回调函数，就会等待该Promise对象的状态发生变化，才会被调用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">"/post/1.json"</span>).then(<span class="function"><span class="keyword">function</span>(<span class="params">post</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> getJSON(post.commentURL);</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span> <span class="title">funcA</span>(<span class="params">comments</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Resolved: "</span>, comments);</span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span> <span class="title">funcB</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Rejected: "</span>, err);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，第一个then方法指定的回调函数，返回的是另一个Promise对象。这时，第二个then方法指定的回调函数，就会等待这个新的Promise对象状态发生变化。如果变为Resolved，就调用funcA，如果状态变为Rejected，就调用funcB。</p>
<h4 id="Promise-prototype-catch()">Promise.prototype.catch()</h4><p>Promise.prototype.catch方法是<code>.then(null, rejection)</code>的别名，用于指定发生错误时的回调函数。</p>
<figure class="highlight scilab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">"/posts.json"</span>).<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(posts)</span> &#123;</span></span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;).<span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span><span class="params">(error)</span> &#123;</span></span><br><span class="line">  <span class="comment">// 处理前一个回调函数运行时发生的错误</span></span><br><span class="line">  <span class="transposed_variable">console.</span>log(<span class="string">'发生错误！'</span>, error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，getJSON方法返回一个Promise对象，如果该对象状态变为Resolved，则会调用then方法指定的回调函数；如果异步操作抛出错误，状态就会变为Rejected，就会调用catch方法指定的回调函数，处理这个错误。</p>
<p>下面是一个例子。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'test'</span>)</span><br><span class="line">&#125;);</span><br><span class="line">promise.catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123; <span class="built_in">console</span>.log(error) &#125;);</span><br><span class="line"><span class="comment">// Error: test</span></span><br></pre></td></tr></table></figure>
<p>如果Promise状态已经变成resolved，再抛出错误是无效的。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">  resolve(<span class="string">"ok"</span>);</span><br><span class="line">  <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'test'</span>);</span><br><span class="line">&#125;);</span><br><span class="line">promise</span><br><span class="line">  .then(<span class="function"><span class="keyword">function</span>(<span class="params">value</span>) </span>&#123; <span class="built_in">console</span>.log(value) &#125;)</span><br><span class="line">  .catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123; <span class="built_in">console</span>.log(error) &#125;);</span><br><span class="line"><span class="comment">// ok</span></span><br></pre></td></tr></table></figure></p>
<p>Promise对象的错误具有“冒泡”性质，会一直向后传递，直到被捕获为止。也就是说，错误总是会被下一个catch语句捕获。</p>
<figure class="highlight scilab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">getJSON(<span class="string">"/post/1.json"</span>).<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(post)</span> &#123;</span></span><br><span class="line">  <span class="keyword">return</span> getJSON(<span class="transposed_variable">post.</span>commentURL);</span><br><span class="line">&#125;).<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">(comments)</span> &#123;</span></span><br><span class="line">  <span class="comment">// some code</span></span><br><span class="line">&#125;).<span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span><span class="params">(error)</span> &#123;</span></span><br><span class="line">  <span class="comment">// 处理前面三个Promise产生的错误</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，一共有三个Promise对象：一个由getJSON产生，两个由then产生。它们之中任何一个抛出的错误，都会被最后一个catch捕获。</p>
<p>跟传统的try/catch代码块不同的是，如果没有使用catch方法指定错误处理的回调函数，Promise对象抛出的错误不会传递到外层代码，即不会有任何反应。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> someAsyncThing = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 下面一行会报错，因为x没有声明</span></span><br><span class="line">    resolve(x + <span class="number">2</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">someAsyncThing().then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'everything is great'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上面代码中，someAsyncThing函数产生的Promise对象会报错，但是由于没有调用catch方法，这个错误不会被捕获，也不会传递到外层代码，导致运行后没有任何输出。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">  resolve(<span class="string">"ok"</span>);</span><br><span class="line">  setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'test'</span>) &#125;, <span class="number">0</span>)</span><br><span class="line">&#125;);</span><br><span class="line">promise.then(<span class="function"><span class="keyword">function</span>(<span class="params">value</span>) </span>&#123; <span class="built_in">console</span>.log(value) &#125;);</span><br><span class="line"><span class="comment">// ok</span></span><br><span class="line"><span class="comment">// Uncaught Error: test</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Promise指定在下一轮“事件循环”再抛出错误，结果由于没有指定try-catch语句，就冒泡到最外层，成了未捕获的错误。</p>
<p>Node.js有一个unhandledRejection事件，专门监听未捕获的reject错误。</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">process.<span class="keyword">on</span>(<span class="string">'unhandledRejection'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, p)</span> <span class="comment">&#123;</span><br><span class="line">  console.error(err.stack)</span><br><span class="line">&#125;</span>);</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，unhandledRejection事件的监听函数有两个参数，第一个是错误对象，第二个是报错的Promise实例，它可以用来了解发生错误的环境信息。。</p>
<p>需要注意的是，catch方法返回的还是一个Promise对象，因此后面还可以接着调用then方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> someAsyncThing = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 下面一行会报错，因为x没有声明</span></span><br><span class="line">    resolve(x + <span class="number">2</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">someAsyncThing().then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> someOtherAsyncThing();</span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'oh no'</span>, error);</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'carry on'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// oh no [ReferenceError: x is not defined]</span></span><br><span class="line"><span class="comment">// carry on</span></span><br></pre></td></tr></table></figure>
<p>catch方法之中，还能再抛出错误。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> someAsyncThing = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 下面一行会报错，因为x没有声明</span></span><br><span class="line">    resolve(x + <span class="number">2</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">someAsyncThing().then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> someOtherAsyncThing();</span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'oh no'</span>, error);</span><br><span class="line">  <span class="comment">// 下面一行会报错，因为y没有声明</span></span><br><span class="line">  y + <span class="number">2</span>;</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'carry on'</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// oh no [ReferenceError: x is not defined]</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，catch方法抛出一个错误，因为后面没有别的catch方法了，导致这个错误不会被捕获，也不会传递到外层。如果改写一下，结果就不一样了。</p>
<figure class="highlight scilab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">someAsyncThing().<span class="keyword">then</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span> &#123;</span></span><br><span class="line">  <span class="keyword">return</span> someOtherAsyncThing();</span><br><span class="line">&#125;).<span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span><span class="params">(error)</span> &#123;</span></span><br><span class="line">  <span class="transposed_variable">console.</span>log(<span class="string">'oh no'</span>, error);</span><br><span class="line">  <span class="comment">// 下面一行会报错，因为y没有声明</span></span><br><span class="line">  y + <span class="number">2</span>;</span><br><span class="line">&#125;).<span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span><span class="params">(error)</span> &#123;</span></span><br><span class="line">  <span class="transposed_variable">console.</span>log(<span class="string">'carry on'</span>, error);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// oh no [ReferenceError: x is not defined]</span></span><br><span class="line"><span class="comment">// carry on [ReferenceError: y is not defined]</span></span><br></pre></td></tr></table></figure>
<h4 id="Promise-all()">Promise.all()</h4><p>Promise.all方法用于将多个Promise实例，包装成一个新的Promise实例。</p>
<figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="label">var</span> p = Promise.all([<span class="literal">p1</span>,<span class="literal">p2</span>,<span class="literal">p3</span>])<span class="comment">;</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，Promise.all方法接受一个数组作为参数，p1、p2、p3都是Promise对象的实例。（Promise.all方法的参数不一定是数组，但是必须具有Iterable接口，且返回的每个成员都是Promise实例。）</p>
<p>p的状态由p1、p2、p3决定，分成两种情况。</p>
<ol>
<li>只有p1、p2、p3的状态都变成fulfilled，p的状态才会变成fulfilled，此时p1、p2、p3的返回值组成一个数组，传递给p的回调函数。</li>
<li>只要p1、p2、p3之中有一个被rejected，p的状态就变成rejected，此时第一个被reject的实例的返回值，会传递给p的回调函数。</li>
</ol>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 生成一个Promise对象的数组</span></span><br><span class="line"><span class="keyword">var</span> promises = [<span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">13</span>].map(<span class="function"><span class="keyword">function</span><span class="params">(id)</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> getJSON(<span class="string">"/post/"</span> + id + <span class="string">".json"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">Promise.all(promises).then(<span class="function"><span class="keyword">function</span><span class="params">(posts)</span> </span>&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;).<span class="keyword">catch</span>(<span class="function"><span class="keyword">function</span><span class="params">(reason)</span></span>&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="Promise-race()">Promise.race()</h4><p>Promise.race方法同样是将多个Promise实例，包装成一个新的Promise实例。</p>
<figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="label">var</span> p = Promise.race([<span class="literal">p1</span>,<span class="literal">p2</span>,<span class="literal">p3</span>])<span class="comment">;</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，只要p1、p2、p3之中有一个实例率先改变状态，p的状态就跟着改变。那个率先改变的Promise实例的返回值，就传递给p的回调函数。</p>
<p>如果Promise.all方法和Promise.race方法的参数，不是Promise实例，就会先调用下面讲到的Promise.resolve方法，将参数转为Promise实例，再进一步处理。</p>
<h4 id="Promise-resolve()">Promise.resolve()</h4><p>有时需要将现有对象转为Promise对象，Promise.resolve方法就起到这个作用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> jsPromise = <span class="built_in">Promise</span>.resolve($.ajax(<span class="string">'/whatever.json'</span>));</span><br></pre></td></tr></table></figure>
<p>上面代码将jQuery生成deferred对象，转为一个新的Promise对象。</p>
<p>如果Promise.resolve方法的参数，不是具有then方法的对象（又称thenable对象），则返回一个新的Promise对象，且它的状态为Resolved。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.resolve(<span class="string">'Hello'</span>);</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="keyword">function</span> (<span class="params">s</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(s)</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// Hello</span></span><br></pre></td></tr></table></figure>
<p>上面代码生成一个新的Promise对象的实例p。由于字符串Hello不属于异步操作（判断方法是它不是具有then方法的对象），返回Promise实例的状态从一生成就是Resolved，所以回调函数会立即执行。Promise.resolve方法的参数，会同时传给回调函数。</p>
<p>Promise.resolve方法允许调用时不带参数。所以，如果希望得到一个Promise对象，比较方便的方法就是直接调用Promise.resolve方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.resolve();</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>如果Promise.resolve方法的参数是一个Promise实例，则会被原封不动地返回。</p>
<h4 id="Promise-reject()">Promise.reject()</h4><p>Promise.reject(reason)方法也会返回一个新的Promise实例，该实例的状态为rejected。Promise.reject方法的参数reason，会被传递给实例的回调函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="built_in">Promise</span>.reject(<span class="string">'出错了'</span>);</span><br><span class="line"></span><br><span class="line">p.then(<span class="literal">null</span>, <span class="function"><span class="keyword">function</span> (<span class="params">s</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(s)</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 出错了</span></span><br></pre></td></tr></table></figure>
<p>上面代码生成一个Promise对象的实例p，状态为rejected，回调函数会立即执行。</p>
<h4 id="Generator函数与Promise的结合">Generator函数与Promise的结合</h4><p>使用Generator函数管理流程，遇到异步操作的时候，通常返回一个Promise对象。</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">function getFoo() &#123;</span><br><span class="line">  <span class="keyword">return</span> new <span class="type">Promise</span>(function (resolve, reject)&#123;</span><br><span class="line">    resolve('foo');</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> g = function*() &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> foo = <span class="keyword">yield</span> getFoo();</span><br><span class="line">    console.log(foo);</span><br><span class="line">  &#125; catch (e) &#123;</span><br><span class="line">    console.log(e);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">function run(generator) &#123;</span><br><span class="line">  <span class="keyword">var</span> it = generator();</span><br><span class="line"></span><br><span class="line">  function go(<span class="literal">result</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">result</span>.done) <span class="keyword">return</span> <span class="literal">result</span>.value;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">result</span>.value.then(function (value) &#123;</span><br><span class="line">      <span class="keyword">return</span> go(it.next(value));</span><br><span class="line">    &#125;, function (error) &#123;</span><br><span class="line">      <span class="keyword">return</span> go(it.throw(value));</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  go(it.next());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">run(g);</span><br></pre></td></tr></table></figure>
<h4 id="async函数">async函数</h4><p>async函数与Promise、Generator函数一样，是用来取代回调函数、解决异步操作的一种方法。它本质上是Generator函数的语法糖。async函数并不属于ES6，而是被列入了ES7，但是traceur、Babel.js、regenerator等转码器已经支持这个功能，转码后立刻就能使用。</p>

      
    </div>
    <footer class="article-footer">
	  
	  <!-- 百度分享 Start -->
	  <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
	  <!-- 百度分享 End -->
	  
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/">JavaScript</a></li></ul>

	  
<span>
Updated:<time datetime="2015-09-01T02:47:11.000Z" itemprop="dateModified">2015-09-01</time>
</span>


    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/08/28/javascript-oop-function-expression-and-async/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          JavaScript 面向对象程序设计、函数表达式和异步编程
        
      </div>
    </a>
  
  
    <a href="/2015/08/28/javascript-grammar/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">JavaScript 基本语法</div>
    </a>
  
</nav>

  
</article>



<!-- 多说评论框 start -->

<section id="comments">
  <div class="ds-thread"  data-thread-key="/2015/08/28/javascript-reference-type/" data-title="JavaScript 引用类型" data-url="http://howiefh.github.io/2015/08/28/javascript-reference-type/" id="ds_thread">
    <noscript>Please enable JavaScript to view the <a href="//duoshuo.com/?ref_noscript">comments powered by duoshuo.</a></noscript>
  </div>
</section>

<!-- 多说评论框 end -->
</section>
        
          
  <div id="toc" class="toc-aside">
  <h2 class="toc-title">Contents</h2>
    
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#引用类型"><span class="toc-number">1.</span> <span class="toc-text">引用类型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Object类型"><span class="toc-number">1.1.</span> <span class="toc-text">Object类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Array_类型"><span class="toc-number">1.2.</span> <span class="toc-text">Array 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#检测数组"><span class="toc-number">1.2.1.</span> <span class="toc-text">检测数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#转换方法"><span class="toc-number">1.2.2.</span> <span class="toc-text">转换方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#栈方法"><span class="toc-number">1.2.3.</span> <span class="toc-text">栈方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#队列方法"><span class="toc-number">1.2.4.</span> <span class="toc-text">队列方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#重排序方法"><span class="toc-number">1.2.5.</span> <span class="toc-text">重排序方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#操作方法"><span class="toc-number">1.2.6.</span> <span class="toc-text">操作方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#位置方法"><span class="toc-number">1.2.7.</span> <span class="toc-text">位置方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#迭代方法"><span class="toc-number">1.2.8.</span> <span class="toc-text">迭代方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#归并方法"><span class="toc-number">1.2.9.</span> <span class="toc-text">归并方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ES6_新增方法"><span class="toc-number">1.2.10.</span> <span class="toc-text">ES6 新增方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ES7_将加入的方法"><span class="toc-number">1.2.11.</span> <span class="toc-text">ES7 将加入的方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Date_类型"><span class="toc-number">1.3.</span> <span class="toc-text">Date 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#继承的方法"><span class="toc-number">1.3.1.</span> <span class="toc-text">继承的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#日期格式化方法"><span class="toc-number">1.3.2.</span> <span class="toc-text">日期格式化方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#日期/时间组件方法"><span class="toc-number">1.3.3.</span> <span class="toc-text">日期/时间组件方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RegExp_类型"><span class="toc-number">1.4.</span> <span class="toc-text">RegExp 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#RegExp_实例属性"><span class="toc-number">1.4.1.</span> <span class="toc-text">RegExp 实例属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RegExp_实例方法"><span class="toc-number">1.4.2.</span> <span class="toc-text">RegExp 实例方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RegExp_构造函数属性"><span class="toc-number">1.4.3.</span> <span class="toc-text">RegExp 构造函数属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#模式的局限性"><span class="toc-number">1.4.4.</span> <span class="toc-text">模式的局限性</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Function_类型"><span class="toc-number">1.5.</span> <span class="toc-text">Function 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#没有重载"><span class="toc-number">1.5.1.</span> <span class="toc-text">没有重载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数声明与函数表达式"><span class="toc-number">1.5.2.</span> <span class="toc-text">函数声明与函数表达式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#作为值的函数"><span class="toc-number">1.5.3.</span> <span class="toc-text">作为值的函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数内部属性"><span class="toc-number">1.5.4.</span> <span class="toc-text">函数内部属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数属性和方法"><span class="toc-number">1.5.5.</span> <span class="toc-text">函数属性和方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#默认参数"><span class="toc-number">1.5.6.</span> <span class="toc-text">默认参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#rest参数"><span class="toc-number">1.5.7.</span> <span class="toc-text">rest参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#扩展运算符"><span class="toc-number">1.5.8.</span> <span class="toc-text">扩展运算符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#基本包装类型"><span class="toc-number">1.6.</span> <span class="toc-text">基本包装类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Boolean_类型"><span class="toc-number">1.6.1.</span> <span class="toc-text">Boolean 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Number_类型"><span class="toc-number">1.6.2.</span> <span class="toc-text">Number 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#String_类型"><span class="toc-number">1.6.3.</span> <span class="toc-text">String 类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#单体内置对象"><span class="toc-number">1.7.</span> <span class="toc-text">单体内置对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Global对象"><span class="toc-number">1.7.1.</span> <span class="toc-text">Global对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Math_对象"><span class="toc-number">1.7.2.</span> <span class="toc-text">Math 对象</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#键集合类型"><span class="toc-number">1.8.</span> <span class="toc-text">键集合类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Map_类型"><span class="toc-number">1.8.1.</span> <span class="toc-text">Map 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法"><span class="toc-number">1.8.1.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例的属性和操作方法"><span class="toc-number">1.8.1.2.</span> <span class="toc-text">实例的属性和操作方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#遍历方法"><span class="toc-number">1.8.1.3.</span> <span class="toc-text">遍历方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#与其他数据结构的互相转换"><span class="toc-number">1.8.1.4.</span> <span class="toc-text">与其他数据结构的互相转换</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WeakMap_类型"><span class="toc-number">1.8.2.</span> <span class="toc-text">WeakMap 类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Set_类型"><span class="toc-number">1.8.3.</span> <span class="toc-text">Set 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法-1"><span class="toc-number">1.8.3.1.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Set实例的属性和方法"><span class="toc-number">1.8.3.2.</span> <span class="toc-text">Set实例的属性和方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#WeakSet_类型"><span class="toc-number">1.8.4.</span> <span class="toc-text">WeakSet 类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#反射类型"><span class="toc-number">1.9.</span> <span class="toc-text">反射类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Proxy"><span class="toc-number">1.9.1.</span> <span class="toc-text">Proxy</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Reflect"><span class="toc-number">1.9.2.</span> <span class="toc-text">Reflect</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#控制抽象类型"><span class="toc-number">1.10.</span> <span class="toc-text">控制抽象类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Iteration_接口"><span class="toc-number">1.10.1.</span> <span class="toc-text">Iteration 接口</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterable_接口"><span class="toc-number">1.10.1.1.</span> <span class="toc-text">Iterable 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterator_接口"><span class="toc-number">1.10.1.2.</span> <span class="toc-text">Iterator 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#IteratorResult_接口"><span class="toc-number">1.10.1.3.</span> <span class="toc-text">IteratorResult 接口</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#实例"><span class="toc-number">1.10.1.4.</span> <span class="toc-text">实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#默认实现Iterable接口的数据结构"><span class="toc-number">1.10.1.5.</span> <span class="toc-text">默认实现Iterable接口的数据结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterable接口默认的应用场合"><span class="toc-number">1.10.1.6.</span> <span class="toc-text">Iterable接口默认的应用场合</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#原生具备Iterable接口的数据结构"><span class="toc-number">1.10.1.7.</span> <span class="toc-text">原生具备Iterable接口的数据结构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Iterable接口与Generator函数"><span class="toc-number">1.10.1.8.</span> <span class="toc-text">Iterable接口与Generator函数</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise_类型"><span class="toc-number">1.10.2.</span> <span class="toc-text">Promise 类型</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise的含义"><span class="toc-number">1.10.2.1.</span> <span class="toc-text">Promise的含义</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#基本用法-2"><span class="toc-number">1.10.2.2.</span> <span class="toc-text">基本用法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-prototype-then()"><span class="toc-number">1.10.2.3.</span> <span class="toc-text">Promise.prototype.then()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-prototype-catch()"><span class="toc-number">1.10.2.4.</span> <span class="toc-text">Promise.prototype.catch()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-all()"><span class="toc-number">1.10.2.5.</span> <span class="toc-text">Promise.all()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-race()"><span class="toc-number">1.10.2.6.</span> <span class="toc-text">Promise.race()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-resolve()"><span class="toc-number">1.10.2.7.</span> <span class="toc-text">Promise.resolve()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Promise-reject()"><span class="toc-number">1.10.2.8.</span> <span class="toc-text">Promise.reject()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Generator函数与Promise的结合"><span class="toc-number">1.10.2.9.</span> <span class="toc-text">Generator函数与Promise的结合</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#async函数"><span class="toc-number">1.10.2.10.</span> <span class="toc-text">async函数</span></a></li></ol></li></ol></li></ol></li></ol>
    
  </div>

<aside id="sidebar">

  
    
<div class="widget-wrap">
  <h3 class="widget-title">ABOUT ME</h3>
  <ul class="widget about-me">
    
    <li><img class="author" title="About me" src="http://fh-1.qiniudn.com/okal-eltocat.jpg" /></li>
    
    
    <li>Hi,I'm FengHao.</li>
    
    <li>I'll share something interesting and my learning experience with you at this blog.</li>
    
    <li>前博客:<a href="http://hi.baidu.com/idea_star" target="_BLANK">百度空间</a></li>
    
  </ul>
</div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/C/">C</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/">Database</a><span class="category-list-count">13</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MongoDB/">MongoDB</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MySQL/">MySQL</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Eclipse/">Eclipse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/FTP/">FTP</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Git/">Git</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">20</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Java/FreeMarker/">FreeMarker</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/Shiro/">Shiro</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/">JavaEE</a><span class="category-list-count">4</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Hibernate/">Hibernate</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/JSP/">JSP</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Spring/">Spring</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/jQuery/">jQuery</a><span class="category-list-count">1</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Suse/">Suse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Ubuntu/">Ubuntu</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Vim/">Vim</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/编程/">编程</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/软件/">软件</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Android/" style="font-size: 14.75px; color: #65bfa7">Android</a> <a href="/tags/C/" style="font-size: 13.88px; color: #71c1c2">C</a> <a href="/tags/CAS/" style="font-size: 13px; color: #7dc3de">CAS</a> <a href="/tags/Chrome/" style="font-size: 13px; color: #7dc3de">Chrome</a> <a href="/tags/Clean-Code/" style="font-size: 13.88px; color: #71c1c2">Clean Code</a> <a href="/tags/Database/" style="font-size: 13px; color: #7dc3de">Database</a> <a href="/tags/Eclipse/" style="font-size: 13px; color: #7dc3de">Eclipse</a> <a href="/tags/FTP/" style="font-size: 13.88px; color: #71c1c2">FTP</a> <a href="/tags/FreeMarker/" style="font-size: 14.75px; color: #65bfa7">FreeMarker</a> <a href="/tags/Gcc/" style="font-size: 13px; color: #7dc3de">Gcc</a> <a href="/tags/Git/" style="font-size: 14.75px; color: #65bfa7">Git</a> <a href="/tags/Github-Pages/" style="font-size: 13px; color: #7dc3de">Github Pages</a> <a href="/tags/Hexo/" style="font-size: 14.75px; color: #65bfa7">Hexo</a> <a href="/tags/Hibernate/" style="font-size: 13px; color: #7dc3de">Hibernate</a> <a href="/tags/JSP/" style="font-size: 13px; color: #7dc3de">JSP</a> <a href="/tags/JVM/" style="font-size: 14.75px; color: #65bfa7">JVM</a> <a href="/tags/Java/" style="font-size: 14.75px; color: #65bfa7">Java</a> <a href="/tags/JavaMail/" style="font-size: 13px; color: #7dc3de">JavaMail</a> <a href="/tags/JavaScript/" style="font-size: 16.5px; color: #4dbc6f">JavaScript</a> <a href="/tags/Linux/" style="font-size: 13.88px; color: #71c1c2">Linux</a> <a href="/tags/Log/" style="font-size: 13px; color: #7dc3de">Log</a> <a href="/tags/Markdown/" style="font-size: 13.88px; color: #71c1c2">Markdown</a> <a href="/tags/MongoDB/" style="font-size: 20px; color: #1db400">MongoDB</a> <a href="/tags/MySQL/" style="font-size: 13.88px; color: #71c1c2">MySQL</a> <a href="/tags/PHP/" style="font-size: 16.5px; color: #4dbc6f">PHP</a> <a href="/tags/Rhythmbox/" style="font-size: 13px; color: #7dc3de">Rhythmbox</a> <a href="/tags/SSO/" style="font-size: 13px; color: #7dc3de">SSO</a> <a href="/tags/Servlet/" style="font-size: 13px; color: #7dc3de">Servlet</a> <a href="/tags/Shiro/" style="font-size: 13.88px; color: #71c1c2">Shiro</a> <a href="/tags/Spring/" style="font-size: 13.88px; color: #71c1c2">Spring</a> <a href="/tags/Suse/" style="font-size: 13px; color: #7dc3de">Suse</a> <a href="/tags/Thinking-in-Java/" style="font-size: 19.13px; color: #29b61c">Thinking in Java</a> <a href="/tags/Ubuntu/" style="font-size: 17.38px; color: #41ba53">Ubuntu</a> <a href="/tags/Vim/" style="font-size: 18.25px; color: #35b838">Vim</a> <a href="/tags/VirtualBox/" style="font-size: 13px; color: #7dc3de">VirtualBox</a> <a href="/tags/Vsftpd/" style="font-size: 13px; color: #7dc3de">Vsftpd</a> <a href="/tags/jQuery/" style="font-size: 13px; color: #7dc3de">jQuery</a> <a href="/tags/pam-mysql/" style="font-size: 13px; color: #7dc3de">pam_mysql</a> <a href="/tags/小米/" style="font-size: 13px; color: #7dc3de">小米</a> <a href="/tags/软件/" style="font-size: 15.63px; color: #59bd8b">软件</a>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/09/">September 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/08/">August 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/07/">July 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">May 2015</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">April 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/03/">March 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/02/">February 2015</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/12/">December 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/11/">November 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/10/">October 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/09/">September 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/08/">August 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">July 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">June 2014</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/05/">May 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/04/">April 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/03/">March 2014</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/02/">February 2014</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/01/">January 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/12/">December 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/11/">November 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/08/">August 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/07/">July 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/06/">June 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/05/">May 2013</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/04/">April 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">March 2012</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


  
    <div class="widget-wrap">
  <h3 class="widget-title">Calendar</h3>
  <div class="widget">
    <div id="g-calendar" class="g-calendar">
        <span class="g-calendar-prev"></span>
		 
        <span class="g-calendar-back"></span>
        <span class="g-calendar-now"></span>
		 
        <span class="g-calendar-next"></span>
        <div class="g-calendar-hd"></div>
        <div class="g-calendar-tit"></div>
        <div class="g-calendar-bd"></div>
    </div>
  </div>
</div>
<script type="text/javascript">
function LGY_calendar(wrapId, options){
    this.oWrap = this.getId(wrapId);
    this.oHead = this.getByClassName('g-calendar-hd',this.oWrap)[0];
    this.oBody = this.getByClassName('g-calendar-bd',this.oWrap)[0];
    this.oTit = this.getByClassName('g-calendar-tit',this.oWrap)[0];
    this.oPrev = this.getByClassName('g-calendar-prev',this.oWrap)[0];
    this.oNext = this.getByClassName('g-calendar-next',this.oWrap)[0];
    this.oNow = this.getByClassName('g-calendar-now',this.oWrap)[0];
    this.oBack = this.getByClassName('g-calendar-back',this.oWrap)[0];
    this.init();
}
LGY_calendar.prototype = {
    ///////////获取ID元素
    getId:function(id){
        return document.getElementById(id);
    },
    ////////获取css类名元素
    getByClassName:function(className,parent){
        var elem = [],
            node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
            p = new RegExp("(^|\\s)"+className+"(\\s|$)");
        for(var n=0,i=node.length;n<i;n++){
            if(p.test(node[n].className)){
                elem.push(node[n]);
            }
        }
        return elem;
    },
    //填充日历
    fillDate:function(year,month){
        //本月份第一天是星期几-为显示上个月的天数做铺垫
        var first_day = new Date(year,month,1).getDay(),
        //如果刚好是星期天，则空出一行（显示上个月的天数）
            first_day = first_day == 0?first_day=7:first_day;
        //本月份最后一天是几号
        var final_date = new Date(year,month+1,0).getDate(),
        //上个月的最后一天是几号
            last_date = new Date(year,month,0).getDate(),
        //剩余的格子数--即排在末尾的格子数
            surplus = 42 - first_day - final_date;
        //设置年的链接
        var yearHead = "<a href='/" + "archives/" + year + "/'>" + year + " "+ "</a>"; 
        //设置年的链接
        var monthHead = "";
        var month1 = month + 1;
        if (month1 < 10) {
            monthHead = "<a href='/" + "archives/" + year + "/" + "0" + month1 + "/'>" + " " + month1 + " " + "</a>";
        } else {
            monthHead = "<a href='/" + "archives/" + year + "/" + month1 + "/'>" + " " + month1 + " " + "</a>";
        }
        //设置表头的日历
        this.oHead.innerHTML = yearHead+'年'+monthHead+'月';
        //填充日历执行
        var html = '';
        //上个月的显示天数
        for(var i=0;i<first_day;i++){
            html+='<span class="g-calendar-grey">'+(last_date-(first_day-1)+i)+'</span>';
        }
        //本月的显示天数
        var postdate = new Date("Fri Aug 28 2015 12:18:03 GMT+0800"); 
        if (true && postdate.getFullYear() == year && postdate.getMonth() == month) { 
            html += '<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span><a href="/2015/08/10/java-web/" title="Java Web 笔记">10</a></span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span>26</span><span>27</span><span><a href="/2015/08/28/javascript-reference-type/" title="当天有3篇博客,第一篇:JavaScript 引用类型">28</a></span><span>29</span><span>30</span><span>31</span>';
        } else {
            for(var j=0;j<final_date;j++){        
                html+='<span id="d'+(j+1)+'">'+(j+1)+'</span>';
            }
        }
        //下个月的显示天数
        for(var k=0;k<surplus;k++){
            html+='<span class="g-calendar-grey">'+(k+1)+'</span>';
        }
        //fill
        this.oBody.innerHTML = html;
        // 当前状态
        if(year==this.c_year&&this.c_month==month){
            this.oBody.getElementsByTagName('span')[first_day+this.date-1].className='g-calendar-on';
        }

        // 对所有文章遍历,然后将有文章的日期加上链接,如果文章太多的话,生成页面会很大,去掉了
        
    },
    // next切换
    next:function(){
        var _that = this;
        this.oNext.onclick = function(){
            _that.month++;
            if(_that.month>11){
                _that.month = 0;
                _that.year++;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    // back 切换
    back:function(){
        var _that = this;
        if(this.oBack != undefined) {
            this.oBack.onclick = function(){
                var postdate = new Date("Fri Aug 28 2015 12:18:03 GMT+0800"); 
                _that.year = postdate.getFullYear();
                _that.month = postdate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // now切换
    now:function(){
        var _that = this;
        if(this.oNow != undefined ) {
            this.oNow.onclick = function(){
                var nowDate = new Date(); 
                _that.year = nowDate.getFullYear();
                _that.month = nowDate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // prev切换
    prev:function(){
        var _that = this;
        this.oPrev.onclick = function(){
            _that.month--;
            if(_that.month<0){
                _that.month = 11;
                _that.year--;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    init:function(){
        this.oTit.innerHTML = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>';
        // 获取今天的日历时间
        var now = new Date();
        this.c_year = this.year = now.getFullYear();
        this.c_month = this.month = now.getMonth();
        this.date = now.getDate();
        // 初始化--填充日历
        this.fillDate(this.year,this.month);
        //next切换
        this.next();
        //prev切换
        this.prev();
        //back 切换
        this.back();
        //now 切换
        this.now();
    }
}
new LGY_calendar('g-calendar');
</script>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2015/09/01/javascript-summary/">JavaScript 总结</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-grammar/">JavaScript 基本语法</a>
          </li>
        
          <li>
            <a href="/2015/08/10/java-web/">Java Web 笔记</a>
          </li>
        
      </ul>
    </div>
  </div>


  
    
<div class="widget-wrap">
  <h3 class="widget-title">Recent Comments</h3>
  <ul class="widget ds-recent-comments" data-num-items="5" data-show-avatars="0" data-show-title="1" data-show-time="1"></ul>
</div>
<!-- 需要多说的公用代码 -->


  

</aside>

        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2015 howiefh<br>
      Powered by <a href="http://zespia.tw/hexo/" target="_blank">Hexo</a> and Theme by <a href="https://github.com/howiefh/hexo-theme-landscape-f" target="_blank" title="Landscape-F">Landscape-F</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<!-- 多说公共JS代码 start (一个网页只需插入一次) -->

<script type="text/javascript">
  var duoshuoQuery = {short_name:"howiefh"};
  (function() {
	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	(document.getElementsByTagName('head')[0] 
		|| document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script> 

<!-- 多说公共JS代码 end -->

<!-- 百度分享 start -->

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":["mshare","douban","bdysc","sqq","qq","hi","baidu","huaban","youdao","sdo","mail","xg","diandian","fx","copy","print"],"bdPic":"","bdStyle":"1","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"分享到：","viewSize":"16"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

<!-- 百度分享 end -->

<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="/js/jquery.min.js"></script>
-->
<script src="/js/jquery.min.js" type="text/javascript"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<div class="bottom-btn">

	<a class="icon-gotop" href="javascript:void(0)" title="返回顶部"></a>
	<script src="/js/gotop.js" type="text/javascript"></script>
	<!--
	<script src="/js/gotop.js"></script>
	-->


	<a class="icon-toc-toggle" href="javascript:void(0)" title="文章目录"></a>
	<!--
	<script src="/js/toc_aside_toggle.js"></script>
	-->

</div>
<script src="/js/toc_aside_toggle.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>
